The value and address of method in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In Golang, the method of the struct is in the following form:

func (R receivertype) funcName (parameters) (results)

If you want to modify the value of a struct's members, the method is defined when its receivertype must be in struct* form. If Receivertype is a struct, the value of the struct member cannot be changed.

Less nonsense, code validation:

Package Mainimport (    "FMT") type tag struct {    value int32}func (_tag tag) change () {    _tag.value = int32 (987)}ty PE tag2 struct {    value Int32}func (_tag *tag2) Change2 () {    _tag.value = int32 (987)}func main () {    _tag: = new (t AG)    _tag.value = 123     _tag. Change ()    FMT. Println (_tag)    _tag. Change ()    FMT. Println (_tag)    _tag2: = tag2{41}    _tag2. Change2 ()    FMT. Println (_TAG2)    _tag2. Change2 ()    FMT. Println (_TAG2)}

In the main function above, the object _tag in the first piece of code is *tag, but its method change cannot alter its value. In the second code, the object _tag is in the form of *ag, but its method change can alter its value.

If anyone is interested, I will go on to say.

The first parameter of method in Golang is its receivertype, and the method in C-system language such as C + + and its similar language Java is class* this by default. In other words, the method in Golang has a value of two objects and the address of the object, and the C language enforces the address of the object to be passed.

So, you can understand that, right?

Related Article

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.