Parsing the struct structure in programming the Go language

  • 2020-05-30 20:22:09
  • OfStack

struct is similar to C in that it simulates the functionality of class, but not completely! No constructors etc!
struct statement --


package main import "fmt" type Person struct {
 Age  int
 Name string
} func main() {
 // Initialize both
 a := Person{}
 a.Age = 2
 a.Name = "widuu"
 fmt.Println(a)
 b := Person{
  Age:  24,
  Name: "widuu",
 }
 fmt.Println(b)
}

go pointer operation
As follows, we need to change the value. First, we need to fetch the memory address, and then change its reference on the memory address

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) the use of anonymous internal structures

 func main() {
  a := struct {
   name string
   Age  int
  }{
   name: "widuu",
   Age:  19,
  }
  fmt.Println(a)
}


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) the anonymous class value does not need the data name, and the two structures must be the same when the value is assigned

package main import "fmt" type Person struct {
 string
 int
} func main() {
 a := Person{"joe", 19}
 var b Person
 b = a
 fmt.Println(b)
}

The embedded structure
(1). Embedded structure simulation other programs have a concept of inheritance, just a concept

package main import "fmt" type Person struct {
 Name string
 Age  int
}
type student struct {
 Person
 work string
} func main() {
// instantiation 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

package main import "fmt" type A struct {
 Name string  // This is a common uppercase If it's lowercase name You can use a private one within the package
}
type B struct {
 Name string
} func main() {
 a := A{}
 b := B{}
 a.print()
 b.print()
}
// through type Different, let's take the name of the same method
func (a *A) print() {
 fmt.Println("A")
} func (b *B) print() {
 fmt.Println("B")
}


Related articles: