当前位置: > > > > 如何将切片转换为固定长度的切片并返回
来源:stackoverflow
2024-04-30 11:51:29
0浏览
收藏
编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天就整理分享《如何将切片转换为固定长度的切片并返回》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
问题内容
如何将 []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)
解决方案
这里有一个 ,可以更清楚地说明 copy(t3[:],vec)
发生了什么。
go 演示示例代码:
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) }
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持!更多关于Golang的相关知识,也可关注公众号。