【Go】Drill interface{}

interface{}

Explore

When set object is an interface{}

  1. Set object is an interface{}
  2. Use pointer to set object value is int / string / struct / slice
  3. Print kind / address / type / value

conclusion

  • The interface{} is changed by each time setting, but the address is not changed.

for example

source

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
package main

import (
	"fmt"
	"reflect"
)

type S struct {
	x int
	y int
}

func main() {

	var i interface{}
	printInfo(&i)

	setInt(&i)
	setStr(&i)
	setStruct(&i)
	setSlice(&i)
}

func setInt(i *interface{}) {
	*i = 999
	printInfo(i)
}

func setStr(i *interface{}) {
	*i = "str"
	printInfo(i)
}

func setStruct(i *interface{}) {
	*i = S{
		x: 1,
		y: 2,
	}
	printInfo(i)
}

func setSlice(i *interface{}) {
	*i = []int{1, 2, 3, 4}
	printInfo(i)
}

func printInfo(i *interface{}) {

	objKind := reflect.ValueOf(*i).Kind()
	objType := fmt.Sprintf("%T", *i)
	objAddress := fmt.Sprintf("%p", *&i)
	objValue := *i
	fmt.Printf("[Kind is : %v]\n", objKind)
	fmt.Printf("% 15v %v\n", "Address =>", objAddress)
	fmt.Printf("% 15s %v\n", "Type =>", objType)
	fmt.Printf("% 15s %+v\n", "Value =>", objValue)
}