在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
package main import "fmt" func main() { s := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9"} //定义切片 fmt.Printf("%v \n", s) s1 := s[0:5] fmt.Printf("%v \n", s1) s2 := make([]string, len(s1)) copy(s2, s1) //slice can use copy fmt.Printf("%v \n", s2) s2 = s1 //slice can use operator = fmt.Printf("%v \n", s2) if &s1 == &s2 { fmt.Println("the silce share the same address") } else { fmt.Println("the silce does not share the same address") }
if &s1 == &s { fmt.Println("the silce share the same address") } else { fmt.Println("the silce does not share the same address") }
type sliceTest struct { number int sliceNum []string }
var sliceTest1 sliceTest var sliceTest2 sliceTest sliceTest1.number = 1 sliceTest1.sliceNum = s1 fmt.Printf("%v \n", sliceTest1) sliceTest2 = sliceTest1 fmt.Printf("%v \n", sliceTest2) sliceTest3 := sliceTest1 fmt.Printf("%v \n", sliceTest3) //var sliceTest4 sliceTest // copy(sliceTest4, sliceTest1) //compil error:arguments to copy must be slices // fmt.Printf("%v \n", sliceTest4) }
C:/Go/bin/go.exe build -i [E:/staff/xc/1.12] 成功: 进程退出代码 0. E:/staff/xc/1.12/1.12.exe [E:/staff/xc/1.12] [1 2 3 4 5 6 7 8 9] [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5] the silce does not share the same address the silce does not share the same address {1 [1 2 3 4 5]} {1 [1 2 3 4 5]} {1 [1 2 3 4 5]} 成功: 进程退出代码 0.
总结: 1.slice可以用copy和操作符= 2.结构体只能用=,不能用copy 3.虽然从silce中取一个小的slice的确是共用一个内存,但是他们采用指针的方式来进行指向,而指针的地址是不同的。 如下图所示: 一个slice由三个部分构成:指针、长度和容量。 |
请发表评论