go切片结构体测试---copy函数与=操作符的区别

 
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由三个部分构成:指针、长度和容量。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值