• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go入门笔记-15Go使用反射发布时间:2022-07-10
下一篇:
Mac下安装和使用Go框架Beego发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap