%T :使用Go语法输出的值的类型
%v:使用默认格式输出的内置或者自定义类型的值,或者是使用其类型的String()方式输出的自定义值,如果该方法存在的话
%p:以十六进制(基数为16)表示的一个值的地址,前缀为0x,字母使用小写的a-f表示
1、浅复制(1)new()和:=
package mainimport "fmt"type dog struct {
name string
ageint
sexint
}func main() {
dog1 := new(dog)
dog1.name = "dog1"
dog1.age = 11
dog1.sex = -1 dog2 := dog1 fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2) dog2.name = "dog2"
dog2.age = 12
dog2.sex = 2
fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2)
}
文章图片
2、浅复制(2)结构名{}和 :=&
package mainimport "fmt"type dog struct {
name string
ageint
sexint
}func main() {
dog1 := dog{
name: "dog1",
age:11,
sex:-1,
}
dog2 := &dog1 fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2) dog2.name = "dog2"
dog2.age = 12
dog2.sex = 2
fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2)
}
文章图片
3、浅复制(3) 切片
package mainimport (
"fmt"
"unsafe"
)func main() {
slice_test := []int{1, 2, 3, 4, 5} fmt.Println(unsafe.Sizeof(slice_test))
fmt.Printf("main:%#v,%#v,%#v\n", slice_test, len(slice_test), cap(slice_test)) slice_value(slice_test)
fmt.Printf("main:%#v,%#v,%#v\n", slice_test, len(slice_test), cap(slice_test)) slice_ptr(&slice_test)
fmt.Printf("main:%#v,%#v,%#v\n", slice_test, len(slice_test), cap(slice_test)) fmt.Println(unsafe.Sizeof(slice_test))
}func slice_value(slice_test []int) {
slice_test[1] = 100// 函数里的slice确实有被修改
slice_test = append(slice_test, 6) // 函数外的不变
fmt.Printf("slice_value:%#v,%#v,%#v\n", slice_test, len(slice_test), cap(slice_test))
}func slice_ptr(slice_test *[]int) { // 这样才能修改函数外的slice
(*slice_test)[1] = 10
*slice_test = append(*slice_test, 7)
fmt.Printf("slice_ptr:%#v,%#v,%#v\n", *slice_test, len(*slice_test), cap(*slice_test))
}
文章图片
unsafe.sizeof()
4、 深复制(1)结构名{}和:=
package mainimport "fmt"type dog struct {
name string
ageint
sexint
}func main() {
dog1 := dog{
name: "dog1",
age:11,
sex:-1,
}
dog2 := dog1 fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2) dog2.name = "dog2"
dog2.age = 12
dog2.sex = 2
fmt.Printf("%T %v %p\n", dog1, dog1, dog1)
fmt.Printf("%T %v %p\n", dog2, dog2, dog2)
}
【go语言深拷贝和浅拷贝】
文章图片
推荐阅读
- Go语言之GRPC
- 通过golang context实现请求超时控制和goroutine生命周期控制
- go protobuf 使用教程(windows环境下)
- 网络协议与网络编程|Go语言进行web开发(二) Go中的Socket编程
- go的gin框架使用(一)(Hello World)
- golang|Go语言入门——从一个简单例子入门
- go语言之脚本命令的使用
- Golang中的"继承"
- 2018|Base58编码解码Go实现