Golang Study notes: How to choose the receiver type of the method

Source: Internet
Author: User

In the process of writing code, often will be involved in the method of receiver type selection problem, often tangled in the use of T or *t, remember the following principles to solve the problem:

  • To modify the instance state, use *t.
  • It is recommended to use T for small objects or fixed values without modifying the state.
  • Large objects are recommended with *t to reduce replication costs.
  • Reference types, strings, dictionaries, functions, and other pointers wrap objects directly with T.
  • If synchronization fields such as mutexes are included, use *T to avoid invalid lock operations due to assignment.
  • Other uncertain situations are *t.

Methods can be invoked using instance values or pointers, and the compiler will automatically convert between the underlying type and pointer type based on the method receiver type.

type N intfunc (n N)Value(){    n++    fmt.Printf("%p, %v\n",&n,n)}func (n *N)Pointer(){    *n++    fmt.Printf("%p, %v\n",n,*n)}func main() {    var a N = 25    p:=&a    a.Value()    a.Pointer()    p.Value()    p.Pointer()    fmt.Printf("%p, %v\n",&a,a)}

In addition, such as the dictionary itself is the pointer wrapper object, the address is not necessary to add & address characters.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.