The general way to define a struct is as follows:
struct { field1 type1 field2 type2 ...}
type T struct {a, b int}
It is also a legal grammar, which is more suitable for simple structures.
var t *new(t)
A variable t
is a T
pointer to a struct field whose value is the 0 value of the type they belong to, and uses the new function to allocate memory to a newer struct variable, which returns a pointer to the allocated memory.
Regardless of whether the variable is a struct type or a struct type pointer, the same selector character (selector-notation) is used to refer to the field of the struct, i.e.:
struct int }var v mystruct // v is struct type variable var p *mystruct // P is a pointer to a struct type variable v.ip.i
struct instance:
Package Mainimport ("FMT" "Strings") Type personstruct{firstNamestringLastNamestring}func Upperson (P*Person ) {P.firstname=strings. ToUpper (p.firstname) p.lastname=strings. ToUpper (P.lastname)}func main () {//1-struct as a value type: varpers1 person Pers1.firstname="Chris"Pers1.lastname="Woodward"Upperson (&pers1) fmt. Printf ("The name of the person is %s%s\n", Pers1.firstname, Pers1.lastname)//2-struct as a pointer:Pers2: =New(person) pers2.firstname="Chris"Pers2.lastname="Woodward" (*PERS2). LastName ="Woodward" //this is legal.Upperson (pers2) fmt. Printf ("The name of the person is %s%s\n", Pers2.firstname, Pers2.lastname)//3-struct as a literal:PERS3: = &person{"Chris","Woodward"} upperson (PERS3) fmt. Printf ("The name of the person is %s%s\n", Pers3.firstname, Pers3.lastname)}
Program output:
IS wasis CHRIS WOODWARD
Use reflection to access the tag tag of a struct:
Package Mainimport ("FMT" "reflect") Type personstruct{firstNamestring' An important answer ' LastNamestring' The name of the Thing '}func main () {TT:= person{" First"," Last"} forI: =0; I <2; i++{Reftag (TT, i)}}
Program output:
Tag:an Important answer Name:firstNameTag:The Name of the thing Name:lastname
Golang Study of the struct