defer
参考李文周老师视频 他的的博客 (liwenzhou.com)
函数结束之前触发,最后输出函数中 return 的返回早于 defer
func main() {
defer fmt.Println(3)
fmt.Println(1)
fmt.Println(2)
}
Slice切片(动态数组)
数组传递拷贝
切片传递指针
数组定义
arr := [10]int{}
var arr [10]int
//遍历 for 循环 和 for range
arr := []int{1,2,3,4}
for i := 0;i < len(arr);i++{
//fmt.Println(arr[i])
}
for _,value := range arr{
fmt.Println(value)
arr[0] = 12
}
四种声明方式
追加片段append(原切片,添加片段)
make([]T, size, cap)
var arr = make([]int,3,5)
arr = append(arr,1)
fmt.Println(cap(arr),len(arr),arr)
//切片的copy()
s := []int{1,2,3,34}
s1 := s[0:2]
s1[0] = 123
fmt.Println(s)
s2 := make([]int,3)
copy(s2,s)
fmt.Println(s2)
//append()
lf := []int{1,2,3}
lf1 := []int{}
s := append(lf1,lf...)
fmt.Println(s)
map(键值对)
make(map[KeyType]ValueType, [cap])
package main
import "fmt"
func printMap(m map[string]string) {
//m是一个引用传递
for k,v := range m{
fmt.Println(k,v)
}
}
func changeMap(c map[string]string) {
c["3"]= "123"
}
func main() {
lf := make(map[string]string)
lf["1"] = "lf"
lf["2"] = "lf2"
lf["3"] = "lf3"
delete(lf,"1")
changeMap(lf)
printMap(lf)
}
//因为是指针类型,拷贝需遍历
originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2
// Create the target map
targetMap := make(map[string]int)
// Copy from the original map to the target map
for key, value := range originalMap {
targetMap[key] = value
}
声明方式
区别
//如果使用make初始化
//slice
slice := make([]type,size,cap)
//map
map := make(map[KeyType]ValueType,[cap])
struct(部分)
基本使用
有深浅拷贝的区别
package main
import "fmt"
type lf int
type Book struct {
title string
auth string
}
func changeBook1(book Book) {
//拷贝副本
book.auth = "nishishei"
}
func changeBook2(book *Book) {
//指针传递
book.auth = "nishishei222"
}
func main() {
//var a lf = 10
//fmt.Printf("%T",a)
var book1 Book
book1.title = "我的名字"
book1.auth = "lf"
fmt.Println(book1)
//
changeBook1(book1)
fmt.Println(book1)
//值改变
changeBook2(&book1)
fmt.Println(book1)
}