首页 > 解决方案 > 如何将切片转换为固定长度的切片并返回

问题描述

如何将 []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)

标签: goslice

解决方案


这是一个Go 操场示例,它可能会更清楚地说明发生了什么copy(t3[:],vec)

去游乐场示例代码:

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)
}

推荐阅读