Go language learning, structure

Recently, the epidemic situation is quite serious, and you can't go out for the new year. If you have nothing to do, continue to update your blog.

Come on, Wuhan!

Let's move on to the structure of go

For example, we want to store a student's information, such as student number, name, age, gender, etc. according to our previous storage habits, we will define different types of fields to represent different fields and different data types.

This method is feasible, but it is relatively troublesome, and is not conducive to data management.

But in GO language, we can store data in the form of structure. Let's look at the definition of structure:

package main

import "fmt"

//Define the structure outside the function, and act globally.
//Definition of structure
//type name struct{
//Structure member list
//}
type Student struct {
	id int
	name string
	sex string
	age int
	addr string
}


func main() {
	//Define structure variables by structure name
	var stdu Student
	//Structure variable name. Member name
	stdu.id = 111
	stdu.name = "Zhang San"
	stdu.sex = "male"
	stdu.age = 26
	stdu.addr = "Chengdu"

	fmt.Println(stdu)
}

Output results:

111 Zhang Sannan 26 Chengdu}

Another way to define:

When writing structure parameters, it is fixed to write according to the defined structure order

func main() {
	var stdu Student=Student{111,"Zhang San", "male", 28, "Chengdu"}
	fmt.Println(stdu)
}

Let's see how automatic derivation types define structs

stdu_1:= Student{age:26, id:222, name:"Li Si", addr:"Chengdu", sex:"male"}

When we define a structure with an auto derived type, we need to add parameters in the structure before defining variables.

2, Assignment and comparison of structures

package main

import "fmt"

type Student struct {
	id   int
	name string
	sex  string
	age  int
	addr string
}

func main() {
	s:= Student{1, "gossip", "male", 18, "Chengdu"}
	//Structure variable assignment
	s1:=s
	fmt.Println(s1)
	//Changing values in a structure
	s1.age=26
	fmt.Println(s1)
	//Let's see if the modified value will affect our original s
	fmt.Println(s)
}

Result:

{1 cheerleader 18 Chengdu}
Cheerleader 26 Chengdu
 {1 cheerleader 18 Chengdu}

We can see that we assign the structure s to s1 for printing, s1, and get the same information as the structure s

After changing the age of s1 to 26, printing s1 and printing s, you can see that changing the value of s1 will not change the value of S.

Structure comparison

//In the structure, for comparison, use "= =" or "! =" to compare, which cannot be greater than or less than.
	if s1!=s{
		fmt.Println("Inequality")
	}else {
		fmt.Println("identical")
	}

Result:

Inequality

In a structure, you can only use "= =" or "! =" for comparison, and cannot use greater than, less than, etc. as comparison of the structure.

Greater than less than can be used to compare structural members.

	if s.age>s1.age{
		fmt.Println("s Older than s1 Age")
	}else {
		fmt.Println("s Less than s1 Age")
	}

Result:

Age of s, less than s1

3, Structure array slicing defined in

We have already introduced the definition and basic use of structure.

1. Structure array

package main

import "fmt"

type student struct {
	id    int
	name  string
	sex   string
	age   int
	score int
	addr  string
}

func main() {
	//var structure variable name structure type
	//Define structure array
	//var structure array name [number of elements] structure type
	var arr[5]student
	// Len (array name) calculates the number of array elements
	//fmt.Println(len(arr))
	for i:=0; i<len(arr) ;i++{
		fmt.Scan(&arr[i].id,&arr[i].name,&arr[i].sex,&arr[i].age,&arr[i].score,&arr[i].addr)

	}
	fmt.Println(arr)
}

Result:

1 ha ha man 18 88 Chengdu
 2 Cheerleading Girls 16 99 Beijing
 3 stupid man 17 77 Shanghai
 4 dada women 15 66 Guangzhou
 5 Gaga male 14 55 Shenzhen
 [{1 ha ha man 18 88 Chengdu} {2 la la woman 16 99 Beijing} {3 stupid man 17 77 Shanghai} {4 Da Da woman 15 66 Guangzhou} {5 GA man 14 55 Shenzhen}]

Input the above data and print the contents of the structure array.

Output the data content of the structure in a circular way

	//fmt.Println(arr)
	//Output each item of the structure through circulation
	for i:=0; i<len(arr); i++ {
		fmt.Println(arr[i])
	}

Result:

1 ha ha man 18 88 Chengdu
 2 Cheerleading Girls 16 99 Beijing
 3 stupid man 17 77 Shanghai
 4 dada women 15 66 Guangzhou
 5 Gaga male 14 55 Shenzhen
 {1 ha ha man 18 88 Chengdu}
{2 cheerleading girl 16 99 Beijing}
{3 stupid man 17 77 Shanghai}
{4 dada female 15 66 Guangzhou}
{5 Gaga male 14 55 Shenzhen}

2. Sorting operation based on member information of structure (bubble sorting algorithm)

package main

import "fmt"

type student struct {
	id    int
	name  string
	sex   string
	age   int
	score int
	addr  string
}

func main() {
	//var structure variable name structure type
	//Define structure array
	//var structure array name [number of elements] structure type
	var arr[5]student
	// Len (array name) calculates the number of array elements
	//fmt.Println(len(arr))
	for i:=0; i<len(arr) ;i++{
		fmt.Scan(&arr[i].id,&arr[i].name,&arr[i].sex,&arr[i].age,&arr[i].score,&arr[i].addr)

	}
	//fmt.Println(arr)
	//Output each item of the structure through circulation
	fmt.Println("Before sorting:")

	for i:=0; i<len(arr); i++ {
		fmt.Println(arr[i])
	}

	//According to the member information of the structure, we use bubble sorting algorithm
	for i:=0; i< len(arr)-1; i++{
		for j:=0;j<len(arr)-1-i;j++{
			//The information, age and score of the members of the comparative structure can be sorted
			if arr[j].age>arr[j+1].age{
				//Exchange members by comparison
				arr[j],arr[j+1]=arr[j+1],arr[j]
			}

		}
	}
	fmt.Println("After sorting:")
	for i:=0; i<len(arr); i++ {
		fmt.Println(arr[i])
	}
}

Result:

1 ha ha man 18 88 Chengdu
 2 Cheerleading Girls 16 99 Beijing
 3 stupid man 17 77 Shanghai
 4 dada women 15 66 Guangzhou
 5 Gaga male 14 55 Shenzhen
 Before sorting:
{1 ha ha man 18 88 Chengdu}
{2 cheerleading girl 16 99 Beijing}
{3 stupid man 17 77 Shanghai}
{4 dada female 15 66 Guangzhou}
{5 Gaga male 14 55 Shenzhen}
After sorting:
{5 Gaga male 14 55 Shenzhen}
{4 dada female 15 66 Guangzhou}
{2 cheerleading girl 16 99 Beijing}
{3 stupid man 17 77 Shanghai}
{1 ha ha man 18 88 Chengdu}

The elements in the array allow the operation of assigning values to each other, and exchange all the data in the members of the structure.

3, Use automatic type derivation to create a structure

package main

import "fmt"

type students struct {
	id    int
	name  string
	sex   string
	age   int
	score int
	addr  string
}


func main() {
	//Creating structure information using automatic type inference
	arr:=[3]students{
		{101,"gossip","male", 50, 99,"Chengdu"},
		{102,"Ha-ha","female",40,100,"Beijing"},
		{103,"Quack", "male",30,88,"Shanghai"},
	}

	for i,v:=range arr{
		//Print type
		//fmt.Printf("%T",v)
		fmt.Println(i,v)
	}
}

Result:

0 {101 cheerleading man 50 99 Chengdu}
1 {102 haha women 40 100 Beijing}
2 {103 Gaga male 30 88 Shanghai}

4. Definition of slice structure:

Difference: [number of elements] array [] slice

arr:=[]students{
		{101,"gossip","male", 50, 99,"Chengdu"},
		{102,"Ha-ha","female",40,100,"Beijing"},
		{103,"Quack", "male",30,88,"Shanghai"},
	}

It can also run printing.

 

package main

import "fmt"

type students struct {
	id    int
	name  string
	sex   string
	age   int
	score int
	addr  string
}


func main() {
	//Creating structure information using automatic type inference
	// [number of elements] array [] slice
	arr:=[]students{
		{101,"gossip","male", 50, 99,"Chengdu"},
		{102,"Ha-ha","female",40,100,"Beijing"},
		{103,"Quack", "male",30,88,"Shanghai"},
	}

	//Adding data information to slices
	arr = append(arr,students{104,"tick", "male",40,77,"Guangzhou"})
	for i,v:=range arr{
		//Print type
		//fmt.Printf("%T",v)
		fmt.Println(i,v)

	}
}

Result:

0 {101 cheerleading man 50 99 Chengdu}
1 {102 haha women 40 100 Beijing}
2 {103 Gaga male 30 88 Shanghai}
3 {104 dada male 40 77 Guangzhou}

 

4, Structure as value in Map

package main

import "fmt"

type stu struct {
	name  string
	age   int
	score int
}

func main() {
	//Define a map
	m:=make(map[int]stu)
	m[1] = stu{"Ha-ha", 50,88}
	m[2] = stu{"tick",51,88}
	fmt.Println(m)
}

Result:

map[1: {ha ha 50 88} 2: {Da Da 51 88}]

Loop through values in map

	for k,v:=range m{
		fmt.Println(k,v)
	}

Result:

1 {ha ha 50 88}
2 {dada 51 88}

5, Slice of structure as value in map

package main

import "fmt"

type stu struct {
	name  string
	age   int
	score int
}

func main()  {
	//Slice of structure as value in map
	m:=make(map[int][]stu)
	// map structure slice assignment
	m[1] = append(m[1],stu{"Ha ha 1",51,81},
					   stu{"Da Da 1",61,91})
	m[2] = append(m[2],stu{"Ha ha 2",52,82},
	                   stu{"Da Da 2",62,82})
	m[3] = append(m[3],stu{"Ha ha 3",53,83},
				   	   stu{"Da Da 3",63,93})

	//Ergodic operation
	for k,v:=range m{
		//At this time, the type of V is, structure slice.
		//Traversing slice information
		for i,data:=range v{
			fmt.Println("key:",k,"index:",i,"value:",data)
		}
	}
}

Result:

key: 1 index: 0 value: {ha ha 1 51 81}
key: 1 index: 1 value: {dada 1 61 91}
key: 2 index: 0 value: {ha ha 2 52 82}
key: 2 index: 1 value: {dada 2 62 82}
key: 3 index: 0 value: {ha ha 3 53 83}
key: 3 index: 1 value: {dada 3 63 93}

6, Structure as function parameter

package main

import "fmt"

type person struct {
	id int
	name string
	score int
	sex string
}

func test(s person){
	fmt.Println(s.name)
	fmt.Println(s.score)
	fmt.Println(s.sex)
}


func main() {
	stu:=person{1,"Ha-ha", 55,"male"}
	//Structure as function parameter
	test(stu)
}

Result:

Ha-ha
55
 male

Structure as function parameter is value transfer

package main

import "fmt"

type person struct {
	id int
	name string
	score int
	sex string
}

func test(s person){
	s.name = "Da da da"
}


func main() {
	stu:=person{1,"Ha-ha", 55,"male"}
	//Structure as function parameter
	test(stu)
	//As a function parameter, structure is a value transfer.
	fmt.Println(stu)
}

Result: the structure name is not changed, and the value is passed.

Value transfer, parameter unit and parameter unit are different storage areas, and modification will not affect other values. (note here that all slice types are address passing)

{1 ha, 55 men}

Structure slice, passed as parameter address.

package main

import "fmt"

type person struct {
	id int
	name string
	score int
	sex string
}

//All slices are address passing
func test(stu []person){
	stu[0].name = "tick"
}


func main() {
	//Defining structural slices
	stu:=[]person{{1,"Ha-ha", 55,"male"},
				  {2,"gossip", 88,"female"}}
	//Add data to slice
	stu = append(stu,person{3,"Quack",66,"male"})
	//Structure slice as function parameter is address passing
	//Structure array as function parameter is value passing
	test(stu)
	fmt.Println(stu)
}

Result:

[{1 dada 55 male} {2 Lala 88 female} {3 Gaga 66 male}]

62 original articles published, 47 praised, 570000 visitors+
Private letter follow

Tags: less Go

Posted on Sat, 01 Feb 2020 03:00:34 -0500 by ljschrenk