1. 程式人生 > >go切片結構體測試---copy函式與=操作符的區別

go切片結構體測試---copy函式與=操作符的區別

packagemain
import"fmt"
funcmain(){
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)//slicecanusecopy
fmt.Printf("%v\n",s2)
s2=s1//slicecanuseoperator=
fmt.Printf("%v\n",s2)
if&s1==&s2{
fmt.Println("thesilcesharethe
sameaddress")
}else{
fmt.Println("thesilcedoesnotsharethesameaddress")
}
if&s1==&s{
fmt.Println("thesilcesharethesameaddress")
}else{
fmt.Println("thesilcedoesnotsharethesameaddress")
}
typesliceTeststruct{
numberint
sliceNum[]string
}
varsliceTest1sliceTest
varsliceTest2sliceTest
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)
//varsliceTest4sliceTest
//copy(sliceTest4,sliceTest1)//compilerror:argumentstocopymustbeslices
//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由三個部分構成:指標、長度和容量。