go20/day02/array/main.go
yumaojun03 f1fbed05d2 ```
feat(array): 添加数组拷贝和遍历的学习内容

添加了数组拷贝的详细说明,包括值拷贝的概念和示例代码,
以及数组遍历的方法介绍。同时创建了相应的演示程序和
draw.io图表来可视化数组拷贝过程。
```
2026-01-11 12:41:00 +08:00

54 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
func main() {
/*
数组拷贝
*/
// ipv4 4字节表示一个ipv4地址, 简短声明: 127.0.0.1
ip := [4]byte{127, 0, 0, 1}
fmt.Println("ip1:", ip)
// 如何copy这个数组, 这个赋值有没有完成copy
// 怎么理解数组的复制 是值拷贝
//
// a := 1
// b := a
// b = 2
// fmt.Println("a:", a)
// fmt.Println("b:", b)
// 数组: 一片连续的地址控制
// ip2 := ip ip 有自己连续的地址空间)
// ip2[4]byte{} (ip2 申请的连续地址)
// Go 默认是值拷贝(重要)
// ip 的值 传递给 ip2
// ip2 和 ip 是两个不同的数组, 互不影响
ip2 := ip
fmt.Println("ip2:", ip2)
// 修改ip2 不会影响ip
ip2[0] = 10
fmt.Println("ip1:", ip)
fmt.Println("ip2:", ip2)
/*
数组遍历
*/
// 1. 通用遍历法(不局限于数组, 切片, map, 字符串)
// 对象的编号,通常叫索引, index (0, ...)
// (0, 1, 2, 3)
// 1. for : 定义变量(开始元素的索引0), 条件(循环结束条件, 不满足条件,结束循环), 变化(索引加1 找下一个元素)
// len 函数: 求数组的长度
// 127 0 0 1
// for i := 0; i < len(ip); i++ {
// fmt.Println(ip[i])
// }
// range 专用遍历法, 语法糖,更简洁, 自动处理索引的变化
for i := range len(ip) {
fmt.Println(ip[i])
}
}