The implementation of the method and interface in "Golang Foundation" Go language

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

Let's look at an interview question: Can the following code compile the past? Why?

package mainimport (    "fmt")type People interface {    Speak(string) string}type Stduent struct{}func (stu *Stduent) Speak(think string) (talk string) {    if think == "bitch" {        talk = "You are a good boy"    } else {        talk = "hi"    }    return}func main() {    var peo People = Stduent{}    think := "bitch"    fmt.Println(peo.Speak(think))}

The answer is no, prompt stduent does not implement people (Speak method has pointer receiver), the fix is var peo people = &stduent{}, assigned to the pointer

In the Go language, functions and methods are different, functions are not receivers, and methods are receivers and belong to a struct.

There are two types of recipients: value receivers (passed by value), pointer receivers (passed by pointer, may change incoming parameters)

Before I saw there was a place to explain: pointer receivers method can both transmit the value and can pass the pointer, including the value receivers method.

My previous understanding was also wrong.

This is not the case, value receivers and pointer receivers are clearly differentiated, people interface is value receivers, and student implements pointer Receivers the Speak method, so student did not implement Peple.

In fact, the pointer receivers method simply converts the M.speak () to (&m). Speak (), as mentioned in the official Go tour, the go compiler saves you a step to take the address.

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.