Go core development study notes (Nianer) - the difference between the function and method

The difference between the functions and methods

  1. The function parameter passing, value type is a value type, a reference type is a reference type, can not be mixed, not the pointer passed value type parameter.
  2. Parameter passing method, depending on the value and reference types func (x x_type) () {...} -> x_type or * x_type
  3. X parameter passed in either a pointer type or value type here can pass compiler and processed in the same manner, i.e. == x & x, is illustrated <structure variables> <field structure> == <Structure & variable body> <field structure>, my.Name == (& My) .Name
  4. Incoming front structure variables described, the method can not be changed later in the specific field value of the initialization process depends on the type of x_type, is consistent with this function, the function of the type Mylist assignment field value change does not affect the main () to initialize the value field, * Mylist type field value is assigned the function of the impact main () initializes changing field values.

Often digging interview is here, for example the following program instructions

package main

import "fmt"

type Mylist struct {
	Name string
	Age string
}

func (my Mylist) value_type() {
	fmt.Println("都能传,但是到这儿都是值类型")
}

func (my *Mylist) ptr_type() {
	my.Name = "zzz"
	fmt.Println("都能传,但是到这儿都是引用类型")
}

func ptr1_type(my *Mylist) {
	fmt.Println("只能传指针类型")
}

func value1_type(my Mylist) {
	fmt.Println("只能传值类型")
}

func main() {
	var my Mylist          //定义一个结构体实例
	my.Name = "lululu"     //初始化结构体实例my中的字段Name为"lululu"
	
	my.value_type()         //对于方法中,由于编译器优化,传递的结构体变量既可以是值也可以是地址
	fmt.Println(my.Name)    //无论是my为值还是地址,最终传递给绑定变量的都是值拷贝
	(&my).value_type()      
	fmt.Println((&my).Name)

	my.ptr_type()           //但是具体的my.Name的值还是要看结构体绑定变量到底是值类型还是指针类型
	fmt.Println(my.Name)    //结构体变量为值类型,则方法内值的改变不影响main()中初始化变量的值
	(&my).ptr_type()        //结构体变量若为引用类型,则方法内值的改变影响main()中初始化变量的值
	fmt.Println((&my).Name)

	value1_type(my)         //函数中不存在传入绑定变量,所以和之前一样,值类型只能传值类型,地址类型只能传地址类型,不可my和&my代表一个意思
	ptr1_type(&my)          //值类型函数内的改变不影响main()初始化变量的值,引用类型函数内的改变影响main()初始化变量的值,
}
Published 49 original articles · won praise 18 · views 4005

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/90142613