Home >Backend Development >Golang >How to define structure method in go language

How to define structure method in go language

青灯夜游
青灯夜游Original
2023-01-17 14:06:412630browse

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.

How to define structure method in go language

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 ReceiverThe 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)

Define structure method

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)
}

Pointer receiver

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn