How to define structure method in go language
How to define structure methods in Go language: 1. Define a structure with the syntax "type point struct {....}"; 2. Use the structure as a receiver to define the structure method, Syntax "func (receiver variable receiver type) method name (parameter list) (return value list) {//method body}". In Go language, the type of receiver can be any type, not just structure, but also any type other than struct type.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Structure method
Go language has both functions and methods. The essence of methods is functions, but methods and functions have different points.
Function A function is a piece of code with independent functions that can be called multiple times to achieve code reuse.
Method method is the behavioral function of a class, which can only be called by objects of this class.
The method of Go language is a function that acts on a specific type of variable. This specific type of function is called Receiver
The concept of a receiver is similar to the this or self keywords in object-oriented languages.
The receiver of the Go language emphasizes that methods have action objects, while functions have no action objects.
In Go language, the type of receiver can be any type, not just structure, but also any type other than struct type. (Such as integers, strings, slices, maps, and even functions, etc.)
As long as the receivers are different, the method names can be the same.
There are overridden methods but no overloaded methods(overloaded methods are not supported, that is, methods with the same name but different parameters cannot be defined)
The receiver can be a struct type or a non-struct type, can be a pointer type and a non-pointer type.
When naming variables in the receiver, it is officially recommended to use the first lowercase letter of the receiver type.
// 定义方法的语法格式: func (接收者变量 接收者类型) 方法名(参数列表) (返回值列表){ //方法体 } // 定义结构体 type point struct { X int Y int } // 定义结构体方法 func (p point) print() { fmt.Println(p.X, p.Y) }
The go function will copy each actual parameter variable, if an actual parameter is too large And if we want to avoid copying the entire argument, we can use a pointer to pass the address of the variable.
When the pointer receiver calls a method, the compiler will implicitly convert the variable.
type point struct { X int Y int } func (p point) Print() { fmt.Println(p.X, p.Y) } func (p *point) ScaleBy(factor int) { p.X *= factor p.Y *= factor } func main() { p := point{1,1} ptr := &p p.Print() //1. 正确 ptr.Print() //2. 正确 p.ScaleBy(2) //3. 正确 ptr.ScaleBy(2) //4. 正确 point{1,1}.Print() //5. 正确 (&point{1,1}).Print() //6. 正确 (&point{1,1}).ScaleBy( 2) //7. 正确 point{1,1}.ScaleBy( 2) //8. 错误 }
nil is a legal receiver: just like some functions allow nil pointers as actual parameters, the receiver of methods allows nil pointers
// 定义结构体 type A struct { Data int } // 定义结构体方法 func (a *A) FunPtrA() { fmt.Println("FunPtrA") } func main() { // 声明结构体变量 var ptrA *A // 将 nil 赋值给结构体变量 ptrA = nil // 调用结构体方法 ptrA.FunPtrA() //FunPtrA }
Inheritance and overriding of methods
// 声明 human 结构体 type human struct { name, phone string age int8 } // student 继承 human 结构体 所以继承 human 的方法 type student struct { human school string } // employee 继承 human 结构体 所以继承 human 的方法 type employee struct { human company string } // human 定义 sayHi 方法 func (h human) sayHi() { fmt.Printf("我是%s,年龄%d,联系方式%s \n", h.name, h.age, h.phone) } // 方法的继承 func testMethod11(){ // student 继承 human 所以有 sayHi 方法, employee 同理 s1 := student{human{"s1","138001",13},"第一中学"} e1 := employee{human{"e1","138002",30},"第一企业"} s1.sayHi() //我是s1,年龄13,联系方式138001 e1.sayHi() //我是e1,年龄30,联系方式138002 } // 方法的重写 此为重写 非重载 func (s student) sayHi(){ fmt.Printf("我是%s,年龄%d,我在%s上学,联系方式%s \n", s.name, s.age, s.school,s.phone) } func testMethod12(){ s1 := student{human{"s1","138001",13},"第一中学"} s1.sayHi() //我是s1,年龄13,我在第一中学上学,联系方式138001 }
Process-oriented and object-oriented
//面向过程 func Add01(a, b int) int { return a + b } //面向对象,方法:给某个类型绑定一个函数 type long int //tmp叫接收者,接收者就是传递的一个参数 func (tmp long) Add02(other long) long { return tmp + other } func main() { var result int result = Add01(1, 2) //普通函数调用方式 fmt.Println("result = ", result) //定义一个变量 var a long = 2 //调用方式格式: 变量名,函数(所需参数) r := a.Add02(2) fmt.Println("r = ", r) }
[Related recommendations: Go video tutorial, Programming teaching】
The above is the detailed content of How to define structure method in go language. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...
