The difference between methods and functions in Go language

    In Go, there are functions and methods at the same time. The essence of the method is a function, but the method and the function have different points.

difference:

  • The meaning is different
    1.1) Function function is a piece of code with unique functions, which can be called repeatedly to realize code reuse. A method is a function of a class, and only objects of this class can be called.
  • There are receivers in the method, but the function does not have the receiver
    2.1) The method of the Go language is a function that works on a specific type of variable. This specific type of variable is called Receiver (receiver, receiver, receiver);
    2.2) The concept of the recipient is similar to the this or self keywords in the traditional face-to-object language;
    2.3) The recipient of the Go language emphasizes that the method has an action object, but the function does not have an action object;
    2.4) One The method is a function that contains the receiver;
    2.5) In Go, the type of the receiver can be any type, not only a structure, but also any other type except the struct type.
  • The function cannot have the same name, and the method can have the same name
    3.1) As long as the recipient is different, the method name can be the same.
  • The calling method is different. The
    method is called by the struct object through the dot , while the function is called directly.

    The case is as follows:
//myMethod01.go

// myMethodDes project main.go
package main

import (
	"fmt"
)

type Employee struct {
	name, currency string
	salary         int
}

//接收者类型为Employee
func (e Employee) displaySalary() {
	fmt.Println("员工姓名: %s, 薪资: %s%d\n", e.name, e.currency, e.salary)
}

//函数参数为Employee类型
func displaySalary(e Employee) {
	fmt.Printf("员工姓名: %s, 薪资: %s%d\n", e.name, e.currency, e.salary)
}

func main() {
	//fmt.Println("Hello World!")
	emp1 := Employee{
		name:     "Daniel Wang",
		salary:   2000,
		currency: "$", //货币单位
	}

	//调用方法
	emp1.displaySalary()

	//调用函数
	displaySalary(emp1)
}

    The effect is as follows:


Figure (1) The method needs to be called by the object, and the function can be called without the object

Guess you like

Origin blog.csdn.net/sanqima/article/details/108902541