go - 如何将切片转换为固定长度的切片并返回
问题描述
如何将 []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)
解决方案
这是一个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)
}
推荐阅读
- nlp - 如何在文本中搜索(可分离的)短语
- php - 用子类中的特定方法覆盖接口方法签名
- discord.py - 等待 member.add_roles() 不添加角色
- html - 当用户尝试在 iPhone 上的输入中输入文本时,输入字段旁边的按钮被切断
- anylogic - AnyLogic 中的编辑框灵活性
- jenkins - Jenkins 2.249.3 版本无法安装 Veracode Scan 插件
- fortran - 自动分配数组的正确语法
- hibernate - 在用作 ID 的 Embeddable 中忽略 Hibernate FetchMode.JOIN
- r - Bookdown 文档未正确呈现输出
- firebase - 从firebase firestore检索后如何根据字段对firestore集合文档进行排序