From 6e16b0244c2417268d8adbe077e2e20d7da7e301 Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Mon, 20 Sep 2021 02:06:08 +0800 Subject: [PATCH] =?UTF-8?q?docs:=20Slice=20Copy=20=E5=A4=8D=E5=88=B6=20?= =?UTF-8?q?=E5=8F=8A=20=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/slice/copy/main.go | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 base/slice/copy/main.go diff --git a/base/slice/copy/main.go b/base/slice/copy/main.go new file mode 100644 index 0000000..1a81e16 --- /dev/null +++ b/base/slice/copy/main.go @@ -0,0 +1,57 @@ +package main + +import "fmt" + +func main() { + s1 := []int{1, 3, 5} + s2 := s1 + + s3 := make([]int, len(s2), cap(s2)) + // copy 的 目标对象 需 初始化长度 + // 如果 目标对象 的长度为0 则不会 copy 任何东西 + // 如果 目标对象的长度 小于 源对象的长度 则只会 copy 原数组起始位置到目标对象的长度 + copy(s3, s2) + + fmt.Printf("s1 长度: %d, 容量: %d\t%+v\n", len(s1), cap(s1), s1) + fmt.Printf("s2 长度: %d, 容量: %d\t%+v\n", len(s2), cap(s2), s2) + fmt.Printf("s3 长度: %d, 容量: %d\t%+v\n", len(s3), cap(s3), s3) + + fmt.Println("=========================================================") + + s3[1] = 666 + + fmt.Printf("s1 长度: %d, 容量: %d\t%+v\n", len(s1), cap(s1), s1) + fmt.Printf("s2 长度: %d, 容量: %d\t%+v\n", len(s2), cap(s2), s2) + fmt.Printf("s3 长度: %d, 容量: %d\t%+v\n", len(s3), cap(s3), s3) + + fmt.Println("=========================================================") + + s4 := [][3]int{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + + s5 := make([][3]int, len(s4), cap(s4)) + copy(s5, s4) + + fmt.Printf("s4 长度: %d, 容量: %d\t%+v\n", len(s4), cap(s4), s4) + fmt.Printf("s5 长度: %d, 容量: %d\t%+v\n", len(s5), cap(s5), s5) + + fmt.Println("=========================================================") + + // 修改 s5 下标为 0 的 元素 + s5[0] = [3]int{6, 66, 666} + fmt.Printf("s4 长度: %d, 容量: %d\t%+v\n", len(s4), cap(s4), s4) + fmt.Printf("s5 长度: %d, 容量: %d\t%+v\n", len(s5), cap(s5), s5) + + fmt.Println("=========================================================") + + // 删除 s5 中 下标为 1 的元素 + // 切片... 将 切片解构为 不定参数 传参 + // 修改了 底层数组 + s5 = append(s5[:1], s5[2:]...) + fmt.Printf("s4 长度: %d, 容量: %d\t%+v\n", len(s4), cap(s4), s4) + fmt.Printf("s5 长度: %d, 容量: %d\t%+v\n", len(s5), cap(s5), s5) + +}