Error message here!

Hide Error message here!


Error message here!


Hide Error message here!


Error message here!



17. Go language - what is the method

Brother Huanxi 2021-01-21 17:00:51 阅读数:16 评论数:0 点赞数:0 收藏数:0

Video address of this article

Method statement

func( The recipient type / Type a pointer ) Method name ( parameter list )( Return value list {

// Method body 


Through the receiver , The above method is bound to a type . The above method is a method of type , Call the method through an instance of a type or type pointer .

var t T
t.MethodName( parameter list )

var pt *T = &t
pt.MethodName( parameter list )

The first letter of the method name is the export method ( Open )
The method name definition should be placed in the same package as the type definition .

func (t T) X1() Equivalent X1(t T)
When the receiver type is T When ,Go The parameters of the function are value passed , such X1 Yes t Any modification of is on the copy , It won't affect the original T Instance of type .

func (t T) X2() Equivalent X2(t T)
With *T As a recipient , So you are right. t Any changes to the system will directly reflect T In an example of type .

If you want to modify the type instance , So the receiver T Pointer types .
If there is no need to modify the type instance , that T The type and T All types are available ; But when you think about calling a method, the receiver is a copy of the value , If size more , Passing by value results in excessive consumption , Is it or is it T More suitable .


Copyright statement
In this paper,the author:[Brother Huanxi],Reprint please bring the original link, thank you