【Golang】func & pointer

kind

Different kinds use a pointer to change the value in Func.

  • map
  • slice
  • array
  • string
  • struct
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main

import "fmt"

func main() {
	// map
	var mapObj = map[int]string{}
	mapObj[0] = "max"
	updateMapObj(mapObj)
	fmt.Println("   map =>", mapObj)

	// slice
	sliceObj := []string{
		0: "max",
	}
	updateSliceObj(sliceObj)
	fmt.Println(" slice =>", sliceObj) // [sunny]

	// array
	arrayObject := [1]string{"max"}
	updateArrayObj(&arrayObject)
	fmt.Println(" array =>", arrayObject) // [sunny]

	// string
	var stringObj string
	stringObj = "max"
	updateStringObj(&stringObj)
	fmt.Println("string =>", stringObj) // 999

	// struct
	var srtuctObj StructObject
	srtuctObj.name = "max"
	updateStructObj(&srtuctObj)
	fmt.Println("struct =>", srtuctObj) // {sunny}
}

func updateMapObj(mapObj map[int]string) {
	mapObj[0] = "sunny"
}

func updateArrayObj(arrayObject *[1]string) {
	arrayObject[0] = "sunny"
}

func updateSliceObj(sliceObj []string) {
	sliceObj[0] = "sunny"
}

func updateStringObj(stringObj *string) {
	*stringObj = "sunny"
}

type StructObject struct {
	name string
}

func updateStructObj(srtuctObj *StructObject) {
	srtuctObj.name = "sunny"
}