Go structs
Go structs
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
// "strconv"
// "math"
"reflect"
)
// general way how to define struct
type Doctor struct {
// if you capitalize key names -> these will be visible for all the other packages
Number int
ActorName string
Companion []string
}
// anonymous struct
// bDoctor := struct{name string}{name: "John Dou"}
func structs() {
a := Doctor{
Number: 3,
ActorName: "Jon Dou",
Companion: []string{
"one",
"two",
"three",
},
}
fmt.Printf("Printing Doctor struct: %v\n", a)
fmt.Printf("Printing Doctor actorName: %v\n", a.ActorName)
fmt.Printf("Printing Doctor number: %v\n", a.Number)
fmt.Printf("Printing Doctor companion: %v\n", a.Companion)
// I would call these anonymous struct as "lambda struct"
b := struct{name string}{name: "John Dou"}
fmt.Printf("Anonymous struct: %v\n", b)
fmt.Printf("Anonymous struct name: %v\n", b.name)
}
type Animal struct {
Name string
Origin string
}
type Bird struct {
// embedding "Animal" struct
Animal
SpeedKPH float32
CanFly bool
}
// tagging
type WebAPP struct {
Name string `required max:"100"`
Origin string
}
func embedding() {
a := Bird{}
// 1st way how to declare object
a.Name = "Emu"
a.Origin = "Australia"
a.SpeedKPH = 48
a.CanFly = false
fmt.Printf("Embedded struct: %v\n", a)
// 2nd way how to declare Bird object
x := Bird{
Animal: Animal{
Name: "Emu",
Origin: "Australia",
},
SpeedKPH: 30,
CanFly: false,
}
fmt.Printf("Embedded struct: %v\n", x)
// tagging
t := reflect.TypeOf(WebAPP{})
field, _ := t.FieldByName("Name")
fmt.Printf("%v, %T\n", field.Tag, field.Tag)
}
func main() {
// arrays()
// slices()
// maps()
// structs()
embedding()
}
This post is licensed under CC BY 4.0 by the author.
