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!

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

本篇文章带大家了解一下golang 的几种常用的基本数据类型,如整型,浮点型,字符,字符串,布尔型等,并介绍了一些常用的类型转换操作。

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

在写 Go 的过程中经常对比这两种语言的特性,踩了不少坑,也发现了不少有意思的地方,下面本篇就来聊聊 Go 自带的 HttpClient 的超时机制,希望对大家有所帮助。

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。


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

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.