Error message here!

Hide Error message here!

忘记密码?

Error message here!

请输入正确邮箱

Hide Error message here!

密码丢失?请输入您的电子邮件地址。您将收到一个重设密码链接。

Error message here!

返回登录

Close

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 .

image

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

编程之旅,人生之路,不止于编程,还有诗和远方。
阅代码原理,看框架知识,学企业实践;
赏诗词,读日记,踏人生之路,观世界之行;