struct is similar to the C language, simulating the function of class, but not completely! No constructors, etc!
Struct's statement
Copy Code code as follows:
Package Main
Import "FMT"
Type person struct {
Age int
Name string
}
Func Main () {
Initialize two types of
A: = person{}
A.age = 2
A.name = "Widuu"
Fmt. Println (a)
B: = person{
Age:24,
Name: "Widuu",
}
Fmt. Println (b)
}
Go pointer operation
So we're going to change the value, take the memory address, and then change the reference on the memory address.
Copy Code code as follows:
Package Main
Import "FMT"
Type person struct {
Age int
Name string
}
Func Main () {
B: = &person{
Age:24,
Name: "Widuu",
}
Fmt. Println (b)
G (b)
Fmt. Println (b)
}
Func G (per *person) {
Per. Age = 15
Fmt. Println (PER)
}
Anonymous Structure
(1) Use of anonymous internal structure
Copy Code code as follows:
Func Main () {
A: = struct {
Name string
Age int
}{
Name: "Widuu",
Age:19,
}
Fmt. Println (a)
}
Copy Code code as follows:
Package Main
Import "FMT"
Type person struct {
Age int
Name string
member struct {
Phone, city string
}
}
Func Main () {
A: = Person{age:16, Name: "Widuu"}
A.member.phone = "13800000"
a.member.city = "Widuuweb"
Fmt. Println (a)
}
(2) Anonymous class values do not need the data name, at the time of assignment, two structures must be the same
Copy Code code as follows:
Package Main
Import "FMT"
Type person struct {
String
Int
}
Func Main () {
A: = person{"Joe", 19}
var b person
b = A
Fmt. Println (b)
}
Embedded Structure
(1). Embedded structure Simulation Other programs have a concept of inheritance, just concept OH
Copy Code code as follows:
Package Main
Import "FMT"
Type person struct {
Name string
Age int
}
Type student struct {
Person
Work string
}
Func Main () {
When instantiated, if the embedded structure does not have the data structure name, the default is the type name Person:person
A: = Student{person:person{name: "Widuu", age:19}, work: "IT"}
Fmt. Println (a)
}
(2). Structural method
Copy Code code as follows:
Package Main
Import "FMT"
Type A struct {
Name string//This is a shared capitalization if it's lowercase name, it can be used in private.
}
Type B struct {
Name string
}
Func Main () {
A: = a{}
B: = b{}
A.print ()
B.print ()
}
To take the name of the same method, using the type different
Func (a *a) print () {
Fmt. Println ("A")
}
Func (b *b) print () {
Fmt. Println ("B")
}