如何将切片转换为固定长度的切片并返回

时间:2021-02-12 22:48:37

标签: go slice

如何将 []int 转换为 [3]int?

非这些工作:

    vec := []int{1, 2, 3}
    
    t1 := [3]int(vec)
    t2 := [3]int(vec[:])
    //cannot convert vec (variable of type []int) to [3]int
    
    t3 := [3]int{}
    copy(t3, vec)
    //invalid argument: copy expects slice arguments; found t3 (variable of type [3]int) and vec 
    //(value of type []int)

1 个答案:

答案 0 :(得分:0)

这里有一个 Go playground example,可以让您更清楚地了解 copy(t3[:],vec) 的情况。

Go Playground 示例代码:

package main

import (
    "fmt"
)

func main() {
    slice := []int{1, 2, 3, 4}
    var array [3]int
    arrayAsSlice := array[:]      // arrayAsSlice storage IS array; they are aliased.
    copy(arrayAsSlice, slice[:3]) // copy into arrayAsSlice modifies array, too.
    arrayAsSlice[0] = -1          // slice and array are STILL aliased

    arrayAsSlice = append(arrayAsSlice, 99) // slice cannot grow in the memory it has, therefore, it is reallocated.
    arrayAsSlice[0] = 0                     // Now slice and array are NOT aliased, so this does not modify the array

    fmt.Printf("Hello, playground, %+v", array)
}