This is the first day of my participation in Gwen Challenge

I. Structure definition format is as follows:

typeType namestruct{field1field1The type field2field2Type... }Copy the code

Two, three ways of instantiation of structure

1. Basic instantiation

A struct is a type, and can be instantiated as a var, like an integer, a Boolean, or a string.

var t T
//t: struct instance name
//T: struct type
Copy the code

2. The New way

When you instantiate a structure with the new keyword, you get the address of the structure in the following format:

 t := new(T)
 //t: struct instance name
 //T: struct type
Copy the code

T is now a structure pointer.

3. & instantiate the structure address

Fetching the address of a struct with & is equivalent to a new instantiation of the struct type in the following format:

t := T{a,b}
t := &T{} // Equivalent to new(T)
//t: struct instance name
//T: struct type
Copy the code

Example code 1:

package main

import "fmt"

// Define a structure
type dog struct{
	name string
	age int
}

func main(a){
	//1. Use the var keyword to declare the structure type
	var d1 dog
	// The type of the output structure
	fmt.Printf("%T\n",d1)
	
	//2. Create a structure pointer with new
	d3 := new(dog)
	fmt.Printf("%T\n",d3)

	//3. Instantiate by taking the address of the & structure
	d4 := &dog{}
	fmt.Printf("%T\n",d4)
}
Copy the code

Output Result 1:

main.dog
*main.dog
*main.dog
Copy the code

Three ways to initialize a structure

  1. Use. To access structure fields such as dog.name and dog.age for initialization;

  2. Initialize the structure through key-value pairs;

  3. Class using a list of values.

When initializing a structure, you can write values instead of keys, but note:

  • All fields of a structure must be initialized;
  • The order of values must be the same as the order in which fields are declared in the structure;
  • Cannot be mixed with key-value pair initialization

Example code 2:

package main

import "fmt"

// Define a structure
type dog struct{
	name string
	age int
}

func main(a){
	// Declare the structure type with the var keyword
	var d1 dog
	//1. Access the struct field through. To initialize the struct
	d1.name = "Wah"
	d1.age = 1
	fmt.Println(d1)

	//2. Initialize the structure with the key value
	d2 := dog{
		name : "White",
		age : 12,
	} 
	fmt.Println(d2)

	// Create a structure pointer with new
	d3 := new(dog)
	//Go allows access to structure members directly from structure Pointers via
	d3.name = "Cabbage"
	d3.age = 12
	fmt.Println(d3)

	// instantiate by taking the address of the structure
	d4 := &dog{}
	d4.name = "Small"
	d4.age = 13
	fmt.Println(d4)

	//3. Initialize with a list of values
	d5 := dog{
		"Sasha".10,
	}
	fmt.Println(d5)
}
Copy the code

Output Result 2:

{xiaohua 1} {xiaobai 12} &{xiaobai 12} &{Xiaobao 13} {Sasa 10}Copy the code

Note:

D4.name = “packet”, d4.age = 13,

(*d4).name = “packet”,

(*d4).age = 13.