This is a creation in Article, where the information may have evolved or changed.
Golang is a very special language, although it was born late, but in many places and now the programming language is different. Today's programming languages are either functional or object-oriented, while the go language has pointers, structs, and solutions to some of the C-language pits. From this point of view, Golang can be regarded as the pits-enhanced version of C language.
Structural body
Define Structure body
Define structs and C languages, using struct
keywords. Define their member variables and types inside the struct. If the member variables are of the same type, you can write them to the same line.
type Person struct { age int name string}
Initialization
The initialization of a struct requires a special syntax, which is the struct literal . In struct literals, structs can be initialized in order, or they can be initialized by keywords. If you initialize the struct by keyword, you can specify only partial values, and values that are not specified will be initialized with default values.
p1 := Person{24, "易天"}p2 := Person{age: 24, name: "易天"}p3 := Person{age: 24}p4 := Person{name: "张三"}fmt.Println(p1, p2, p3, p4)
Accessing the struct body
The last thing to say is to access the structure. The members of the struct are public, so they can be accessed directly with the dot number .
.
p1.age = 26p1.name = "王五"fmt.Println(p1)
Pointer
The pointer to go
If you learn C language, the concept of pointers should be more familiar. In the go language, the most complex pointer operations are cut off directly, leaving only the operations that get pointers ( &
operators) and get objects ( *
operators).
a, b := 3, 5pa, pb := &a, &bfmt.Println(*pa, *pb)
An implicit dereference
For some complex types of pointers, if you want to access member variables, you need to write a similar (*p).field
form, go provides an implicit dereference feature, we only need to p.field
access the corresponding members.
p1 := &Person{name: "易天", age: 24}fmt.Println((*p1).name)fmt.Println(p1.name)