SoFunction
Updated on 2025-03-03

Detailed explanation of the structure and method of Go language learning

1. Structural alias definition

Variable alias definition

package main

import "fmt"

type integer int

func main() {
	//Type alias definition	var i integer = 1000
	("Value: %d, Type: %T\n", i, i)

	var j int = 100
	j = int(i) 			//j and i do not belong to the same type, and need to be converted	(j)
}

The output result is as follows

Value: 1000, Type:
1000

Structural alias definition

package main

import "fmt"

//Create the structure Studenttype Student struct {
	Number int
}

//Structure definition aliastype Stu Student

func main() {
	//Declare Student type structure	var a Student
	a = Student{30}

	//Declare Stu type structure	var b Stu
	b = Stu{20}

	//Assigning can only be done after a strong turn	a = Student(b)
	("a = %d,type: %T\n", a, a)
	b = Stu(a)
	("b = %d,type: %T\n", b, b)
}

The output result is as follows

a = {20}, type:
b = {20}, type:

2. Factory model

The so-called factory model in Go is actually:

There is a structure that cannot be directly instanced in the package (the first letter of the structure name is lowercase), and an instance that cannot be directly instanced outside the package. So in order to solve this problem, I will write a callable function outside the package and use this function to return the structure object.

package main

import "fmt"

type Student struct {
	Name string
	Age  int
}

func main() {
	//initialization	stu1 := new(Student)
	(stu1)

	//Factory mode processing	stu2 := NewStudent("Zhang San", 18)
	(stu2)
}

//Factory modefunc NewStudent(name string, age int) *Student {
	return &Student{
		Name: name,
		Age:  age,
	}
}

The output result is as follows

&{ 0}
&{Zhang San 18}

Summarize:① makeUsed to createmapslicechannel

② newUsed to createValue Type

3. Tag Original Information

Use when interacting with other languagesJSON format, Some language formats are relatively strict in case specifications. In order to enable Go language to connect with other languages ​​to transmit data, the original Tag information is used to solve the problem.

In layman's terms, it's equivalent to a charging port

Example

package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name  string
	Age   int
	Score float32
}

func main() {
	//initialization	var stu = new(Student)
	 = "stu"
	 = 20
	 = 88

	//Use Json to process structures and convert them into byte arrays	data, err := (stu)
	if err != nil {
		("Error prompt:", err)
		return
	}
	(data)				//Output in byte array	(string(data))		//Convert to string output}

The output result is as follows

[123 34 78 97 109 101 34 58 34 115 116 117 34 44 34 65 103 101 34 58 50 48 44 34 83 99 111 114 101 34 58 56 56 125]
{"Name":"stu","Age":20,"Score":88}

JSON formatted field names

package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	//Json packaged field name	Name  string  `json:"stu_name"`
	Age   int     `json:"stu_age"`
	Score float32 `json:"stu_score"`
}

func main() {
	//initialization	var stu = new(Student)
	 = "stu"
	 = 20
	 = 88

	//Use Json to process structures and convert them into byte arrays	data, err := (stu)
	if err != nil {
		("Error prompt:", err)
		return
	}
	(data)
	(string(data))
}

The output result is as follows

[123 34 115 116 117 95 110 97 109 101 34 58 34 115 116 117 34 44 34 115 116 117 95 97 103 101 34 58 50 48 44 34 115 116 117 95 115 99 111 114 101 34 58 56 56 125]
{"stu_name":"stu","stu_age":20,"stu_score":88}

4. Anonymous field

The field (properties) in the structure have no name, and it is called an anonymous field.

Example

package main

import "fmt"

type Cart struct {
	name  string
	color string
}

type Train struct {
	//Anonymous field	Cart //Implement inheritance	int  //Data type definition can only exist once, and two ints will conflict}

func main() {
	//Initialize the assignment	var t Train		
	 = "train"
	 = "red"
	 = 10		//Directly call the data type assignment	(t)
}

The output result is as follows

{{train red} 10}

Double reference structure, multiple inheritance (the same attribute is defined in the two inherited structures)

package main

import "fmt"

// Parent structuretype Cart struct {
	name  string
	color string
}

// Parent structuretype Box struct {
	color string
}

//Substructuretype Train struct {
	//Anonymous field	Cart //Implement inheritance	Box
	int //Data type definition can only exist once, and two ints will conflict}

func main() {
	//Initialize the assignment	var t Train
	 = "train"
	 = "red"
	 = "blue"
	 = 10 //Directly call the data type assignment	(t)
}

The output result is as follows

{{train red} {blue} 10}

package main

import "fmt"

// Parent structuretype Cart struct {
	name  string
	color string
}

// Parent structuretype Box struct {
	color string
}

//Substructuretype Train struct {
	//Anonymous field	Cart //Implement inheritance	Box
	int   //Data type definition can only exist once, and two ints will conflict	color string
}

func main() {
	//Initialize the assignment	var t Train
	 = "train"
	 = "red" //Cart properties	 = "blue" //Box properties	 = "yellow"   //train's own attributes	 = 10           //Directly call the data type assignment	(t)
}

5. Method

  • The methods in Go are used on variables of a specific type, so custom types can have methods, not juststruct
  • The syntax format is as follows
func (recevier type) methodName(Parameter list)(Return value){}

​​​​​​​recevier type     Specific types,Like pointer、Alias,Structure 
methodName           Method name

Example

package main

import "fmt"

//Define the structuretype Student struct {
	Name string
	Age  int
}

//Define the methodfunc (s Student) init(name string, age int) Student {
	 = name
	 = age
	return s
}

func main() {
	var stu Student
	s := ("zhangsan", 18)
	("s: %v\n", s)
}

Output result

s: {zhangsan 18}

Will the initialized value be returned by defining the return method?

package main

import "fmt"

//Define the structuretype Student struct {
	Name  string
	Age   int
	Score float32
}

//Initialization methodfunc (s *Student) init(name string, age int, score float32) {
	 = name
	 = age
	 = score
	("Initialization is completed")
}

//Return to the structurefunc (s *Student) get() Student {
	return *s
}

func main() {
	var stu Student
	//Define the value	("zhangsan", 18, 90)
	//Return value	stu1 := ()
	(stu1)
}

The output result is as follows

Initialization is completed
{zhangsan 18 90}

Traditional data type customization method, data type conversion

package main

import "fmt"

//Alias ​​Typetype integer int

//Traditional data type customization methodfunc (p integer) convert() string {
	return ("%d", p)
}

func main() {
	var i integer
	i = 100
	s := ()
	("Type:%T, Value:%s\n", s, s)
}

The output result is as follows

Type: string, value: 100

The difference between pointer incoming and value incoming

The value is passed in and will not change the value, and the value can be changed only if the pointer is passed in.

package main

import "fmt"

type integer int

//Traditional data type customization methodfunc (p integer) convert() string {
	return ("%d", p)
}

//Method pass pointer for data synchronization modificationfunc (p *integer) set(b integer) {
	*p = b
}

func main() {
	var i integer
	i = 100
	s := ()
	("Type: %T, Value: %s\n", s, s)
	("Type: %T, Value: %d\n", i, i)
	(200)
	("i: %v\n", i)
}

The output result is as follows

Type: string, value: 100
Type: , Value: 100
i: 200

Method inheritance, combination (anonymous fields are special forms of combination)

package main

import "fmt"

// Parent structuretype Car struct {
	weight int
	name   string
}

// Parent methodfunc (c *Car) Run() {
	("Running")
}

//Substructure Biketype Bike struct {
	//Combination (with name)	c     Car
	wheel int
}

//Substructure Traintype Train struct {
	//anonymous	Car
	wheel int
}

func main() {
	var bike Bike
	 = "bike"
	 = 500
	 = 2

	var train Train
	 = "train"
	 = 140000
	 = 8

	(bike)
	//Method inheritance, call parent structure method	()

	(train)
	//Method inheritance	()
}

The output result is as follows

{{500 bike} 2}
Running
{{140000 train} 8}
Running

package main

import "fmt"

// Parent structuretype Cart struct {
	weight int
	Color  string
}

// Parent methodfunc (c Cart) Run() {
	("Running")
}

//Substructure traintype Train struct {
	Cart
	wheel int
}

//Substructure methodfunc (t Train) String() string {
	str := ("color:[%s],weight:[%d],wheel:[%d]\n", , , )
	return str
}

func main() {
	var train Train
	 = "red"
	 = 14000
	 = 8
	(train)
	()
	("%s\n", train)
}

The output result is as follows

color:[red],weight:[14000],wheel:[8]
​​​​​​​
Running
color:[red],weight:[14000],wheel:[8]

This is the article about the detailed explanation of the structure and method usage of Go language learning. For more related Go language structures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!