第3章:Go语言复合数据类型
1. 数组
1.1 数组声明和初始化
var numbers [5]int
arr1 := [5]int{1, 2, 3, 4, 5}
arr2 := [5]int{1, 2}
arr3 := [...]int{1, 2, 3, 4, 5}
arr4 := [5]int{1: 10, 3: 30}
1.2 数组遍历
numbers := [5]int{10, 20, 30, 40, 50}
for i := 0; i < len(numbers); i++ {fmt.Printf("索引 %d: %d\n", i, numbers[i])
}
for index, value := range numbers {fmt.Printf("索引 %d: %d\n", index, value)
}
for _, value := range numbers {fmt.Println(value)
}
2. 切片(Slice)
2.1 切片的创建和使用
arr := [5]int{1, 2, 3, 4, 5}
slice1 := arr[1:4]
slice2 := []int{1, 2, 3, 4, 5}
slice3 := make([]int, 5)
slice4 := make([]int, 5, 10)
2.2 切片操作
slice := []int{1, 2, 3}
slice = append(slice, 4)
slice = append(slice, 5, 6, 7)
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
slice = append(slice[:2], slice[3:]...)
subSlice := slice[1:4]
2.3 动态扩展
slice := []int{}
for i := 0; i < 20; i++ {slice = append(slice, i)fmt.Printf("长度:%d, 容量:%d\n", len(slice), cap(slice))
}
3. Map
3.1 Map的声明和初始化
ages := make(map[string]int)
ages["Alice"] = 25
ages["Bob"] = 30
scores := map[string]int{"Math": 90,"English": 85,
}
value, exists := scores["Math"]
if exists {fmt.Println("找到值:", value)
}
3.2 Map增删改查
users := map[string]string{}
users["admin"] = "password"
users["admin"] = "newpass"
delete(users, "admin")
for key, value := range users {fmt.Printf("%s: %s\n", key, value)
}
4. 结构体
4.1 结构体定义
type Person struct {Name stringAge int
}
alice := Person{Name: "Alice",Age: 25,
}
student := struct {Name stringAge int
}{Name: "Bob",Age: 20,
}
4.2 方法和接收者
func (p Person) Introduce() string {return fmt.Sprintf("我是%s,今年%d岁", p.Name, p.Age)
}
func (p *Person) Birthday() {p.Age++
}
alice := Person{Name: "Alice", Age: 25}
fmt.Println(alice.Introduce())
alice.Birthday()
4.3 结构体嵌套
type Employee struct {Person Company string
}
type Company struct {employee PersonAddress string
}
emp := Employee{Person: Person{Name: "Charlie", Age: 30},Company: "Google",
}
fmt.Println(emp.Name)
4.4 结构体标签(tag)
type Person struct {Name string `json:"name"`Age int `json:"age"`
}