Understanding interface key points in Go

Source: Internet
Author: User

Interface is the essence of Golang, this paper mainly understand several key points in interface.

I, interface is a collection of method, is also a type

1, the basic function of interface existence is that it defines a set of methods.
We say that interface is a type that can be understood from three points: first, the keywords in its definition form type can be seen. In addition, the formal parameters of the function can be interface type; Finally, interface supports the polymorphism in go, that is, if all the other types implement the interface method, the type implements the interface, which is similar to C + + Inheritance in the.

type Inter interface {    Get() int     Set(int)}

2, go in Allow without any method of interface, this type is called empty interface, because it does not take any method, so can say all types have realized the empty interface.

II, the interface variable stores the value of the implementation type

1, because there are only methods in interface, the formal parameter of the method comes from its implementation type.

package main import "fmt"type Inter interface {    Get() int     Set(int)}type St struct {    Age int }func(s St) Get() int {    return s.Age} func(s *St) Set(age int) {    s.Age = age }func test(i Inter) {    i.Set(10)    fmt.Println(i.Get())}func main() {    s := St{}    test(&s)}

In this code, ST implements the Inter, executes test() , completes the use of the Inter.

2, one of the important uses of interface is reflected in the parameters of the test function, if there are multiple types implemented interface, these types of values can be directly used interface variable storage.

s := S{}var i Interi = &sfmt.Println(i.Get())    //会自动调用S中关于Get的实现

This also shows the polymorphism of Go.

III, Empty interface

1, empty interface no method, so all the types have implemented the empty interface, so, all types can be used as the parameters of the empty interface function:

func doSomething(v interface{}) {}

Since the empty interface can accept any type of argument, is the slice of a interface{} type acceptable to any type of slice? -- No!

package main  import "fmt"func printAll(vals []interface{}) {    for _, val := range vals {        fmt.Println(val)    }}func main() {    names := []string{"hello", "world"}    printAll(names)}

Execution Result:


This example shows that go cannot convert slice to interface{} type slice, but we can convert it manually:

    var interfaceSlice []interface{} = make([]interface{}, len(names))    for i,d := range names {        interfaceSlice[i] = d    }

Execution Result:

Iv. understanding of Receiver

1. The parameter in the Func () in the method defining the struct in Go is called receiver. For example, func(s St) Get() int { } S is the receiver of get. To understand that he can associate the this pointer in C + +.

2, we call the test function in the above example, that is test(&s) , the St pointer type, can you test(s) ?

test(s)the execution result of the call is as follows:

This is a wrong implementation, the key is that Set() the method in the St receiver is a pointer *St .

Interface definition does not stipulate that the method of being idle receiver is the value receiver or pointer receiver, as the above example, when we use test(s) the form of the call, passed to test is a copy of S, In the conversion of S to Inter, the copy of S is Set() a pointer, that is, the receiver of the fast method is not implemented.

If, in turn, receiver is value, the function is called in the form of pointer:

package main import "fmt"type Inter interface {    Get() int     Set(int)}type St struct {    Age int }func(s St) Get() int {    return s.Age} func(s St) Set(age int) {    s.Age = age }func test(i Inter) {    i.Set(10)    fmt.Println(i.Get())}func main() {    s := St{}    test(&s)    test(s)}

The result of the execution is:

The reason why we failed to output 10 10 according to our expectations is that the value of the original data cannot be changed. But the code is functioning properly, that is to say receiver is the value receiver, execution code whether pointer or value can be executed normally.

What is the reason for this phenomenon?
If the incoming pointer,go can find the corresponding value according to pointer, but if it is value, only the copy of value can be passed to temp, there is no way to find the original address of value based on the copy temp of value. This is why pointer can correspond to pointer receiver and value receiver, but value does not meet pointer receiver.

In fact, the key point here is that the argument to the formal parameter is just a copy.

Reference
[1] Understanding the 5 key points of Go interface

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.