Understanding of the Golang interface

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

Understanding Golang's interface mainly lies in the following two points:

    • Interface is a collection of methods
    • Interface is a type

Simple example

package mainimport "fmt"type Animal interface {    Speak() string}type Cat struct{}func (c Cat) Speak() string {    return "cat"}type Dog struct{}func (d Dog) Speak() string {    return "dog"}func Test(params interface{}) {    fmt.Println(params)}func main() {    animals := []Animal{Cat{}, Dog{}}    for _, animal := range animals {        fmt.Println(animal.Speak())    }        Test("string")    Test(123)    Test(true)}

In the above code, animal is defined as an interface, and cat and dog two structures implement the method defined in the interface respectively. When interface{} is used as a function parameter, different types of parameters can be accepted.

Pointers and interface

If the code above is:

func (c Cat) Speak() string {    return "cat"}

Modified to:

func (c *Cat) Speak() string {    return "cat"}

The following error occurs when you run the source code again:

cannot use Cat literal (type Cat) as type Animal in array or slice literal:Cat does not implement Animal (Speak method has pointer receiver)

This is because the program thinks that Cat does not implement the Speak () method, but is implemented by *cat. This means that the struct does not implicitly convert the type when implementing an interface method.

Interface array

interface{} is very different as a function parameter and []interface{} as a formal parameter, as shown in the following example:

package mainimport (    "fmt")func PrintAll(vals []interface{}) {    for _, val := range vals {        fmt.Println(val)    }}func main() {    names := []string{"stanley", "david", "oscar"}    PrintAll(names)}

The above code is not working correctly and the error message is:

cannot use names (type []string) as type []interface {} in argument to PrintAll

This indicates that there must be more than one type conversion operation before assigning a value to an array of interfaces, the correct code is as follows:

package mainimport (    "fmt")func PrintAll(vals []interface{}) {    for _, val := range vals {        fmt.Println(val)    }}func main() {    names := []string{"stanley", "david", "oscar"}    vals := make([]interface{}, len(names))    for i, v := range names {        vals[i] = v    }    PrintAll(vals)}

The above is the basic content about the use of interface.

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.