GO_INTERVIEW_LIB Telegram 571
💬 Можно ли в Go преобразовывать срезы в массивы или указатели на массивы?

Такая возможность была добавлена в Go 1.20. Когда нужно преобразовать срез в массив фиксированного размера, нельзя сделать это напрямую, как показано ниже:

a := []int{0, 1, 2, 3, 4, 5}
var b[3]int = a[0:3]

// cannot use a[0:3] (value of type []int) as [3]int value in variable
// declaration compiler(IncompatibleAssign)


Чтобы преобразовать срез в массив, команда Go обновила эту функцию в Go 1.17. А с выпуском Go 1.20 процесс преобразования стал ещё проще и удобнее с помощью новых литералов:

// Go 1.20
func main() {
a := []int{0, 1, 2, 3, 4, 5}
b := [3]int(a[0:3])

fmt.Println(b) // [0 1 2]
}


// Go 1.17
func main() {
a := []int{0, 1, 2, 3, 4, 5}
b := *(*[3]int)(a[0:3])

fmt.Println(b) // [0 1 2]
}


P. S.: можно использовать a[:3] вместо a[0:3].
15👍112



tgoop.com/go_interview_lib/571
Create:
Last Update:

💬 Можно ли в Go преобразовывать срезы в массивы или указатели на массивы?

Такая возможность была добавлена в Go 1.20. Когда нужно преобразовать срез в массив фиксированного размера, нельзя сделать это напрямую, как показано ниже:

a := []int{0, 1, 2, 3, 4, 5}
var b[3]int = a[0:3]

// cannot use a[0:3] (value of type []int) as [3]int value in variable
// declaration compiler(IncompatibleAssign)


Чтобы преобразовать срез в массив, команда Go обновила эту функцию в Go 1.17. А с выпуском Go 1.20 процесс преобразования стал ещё проще и удобнее с помощью новых литералов:

// Go 1.20
func main() {
a := []int{0, 1, 2, 3, 4, 5}
b := [3]int(a[0:3])

fmt.Println(b) // [0 1 2]
}


// Go 1.17
func main() {
a := []int{0, 1, 2, 3, 4, 5}
b := *(*[3]int)(a[0:3])

fmt.Println(b) // [0 1 2]
}


P. S.: можно использовать a[:3] вместо a[0:3].

BY Библиотека Go для собеса | вопросы с собеседований


Share with your friend now:
tgoop.com/go_interview_lib/571

View MORE
Open in Telegram


Telegram News

Date: |

Avoid compound hashtags that consist of several words. If you have a hashtag like #marketingnewsinusa, split it into smaller hashtags: “#marketing, #news, #usa. The main design elements of your Telegram channel include a name, bio (brief description), and avatar. Your bio should be: Matt Hussey, editorial director at NEAR Protocol also responded to this news with “#meIRL”. Just as you search “Bear Market Screaming” in Telegram, you will see a Pepe frog yelling as the group’s featured image. The Channel name and bio must be no more than 255 characters long During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content.
from us


Telegram Библиотека Go для собеса | вопросы с собеседований
FROM American