GO语言本身是值传递,先给结论,再看case.
标量类型是赋值是值传递,如int float string
数组和结构体赋值也是值传递,如[2]string struct{}
指针赋值也是值传递,只不过传递的是地址而已
map和slice赋值是引用传递,如map[string][string] []string
字符串遍历,得到值是字符,索引是不连续的。如下
标量类型
func TestInt(t *testing.T) { num1 := 123 num2 := num1 num1 = 456 fmt.Println("num1", num1) // num1 456 fmt.Println("num2", num2) // num2 123 } func TestString(t *testing.T) { str1 := "ccb" str2 := str1 str1 = "ccb1" fmt.Println("str1", str1) // str1 ccb1 fmt.Println("str2", str2) // str2 ccb }
数组
func TestArray(t *testing.T) { arr1 := [2]string{"ccb", "123"} arr2 := arr1 arr1[0] = "ccb1" arr2[1] = "1234" fmt.Println("arr1", arr1) // arr1 [ccb1 123] fmt.Println("arr2", arr2) // arr2 [ccb 1234] }
结构体
func TestStruct(t *testing.T) { type P struct { Name string Pass string Maps map[string]string } p1 := P{ Name: "ccb", Pass: "123", Maps: map[string]string{ "key": "val", }, } p2 := p1 p1.Name = "ccb1" p2.Maps["key"] = "val1" p2.Pass = "1234" fmt.Println("p1", p1) // p1 {ccb1 123 map[key:val1]} fmt.Println("p2", p2) // p2 {ccb 1234 map[key:val1]} }
Map
func TestMap(t *testing.T) { map1 := make(map[string]string, 2) map1["name"] = "ccb" map1["pass"] = "123" map2 := map1 map1["name"] = "ccb1" map2["pass"] = "1234" fmt.Println("map1", map1) // map1 map[name:ccb1 pass:1234] fmt.Println("map2", map2) // map2 map[name:ccb1 pass:1234] }
数组遍历
func TestString(t *testing.T) { str := "abc中文" fmt.Println("len(str)=", len(str)) for i, c := range str { fmt.Printf("%v : %v\n", i, string(c)) } } 输出 len(str)= 9 0 : a 1 : b 2 : c 3 : 中 6 : 文