Home >Backend Development >Golang >What is interface in Golang

What is interface in Golang

藏色散人
藏色散人forward
2021-06-18 15:37:141999browse

The following is the interface in Golang introduced by the tutorial column of golang. I hope it will be helpful to friends in need!

Interface in Golang

Let’s talk about the interface first. I understand the interface as a collection of behaviors. Still seems confused. Let’s take a look at the code and allowable effects, then.

package main
import "fmt"
type TypeCalculator interface {
    TypeCal() string
}
type Worker struct {
    Type int
    Name string
}
type Student struct {
    Name string
}
func (w Worker) TypeCal() string {
    if w.Type == 0 {
        return w.Name +"是蓝翔毕业的员工"
    } else {
        return w.Name+"不是蓝翔毕业的员工"
    }
}
func (s Student) TypeCal() string  {
    return s.Name + "还在蓝翔学挖掘机炒菜"
}
func main() {
    worker := Worker{Type:0, Name:"小华"}
    student := Student{Name:"小明"}
    workers := []TypeCalculator{worker, student}
    for _, v := range workers {
        fmt.Println(v.TypeCal())
    }
}
//运行效果
//小华是蓝翔毕业的员工
//小明还在蓝翔学挖掘机炒菜
开始解(xia)释(bai)
首先我们写了一个interface,里面有个待实现的方法TypeCal()
type TypeCalculator interface {
    TypeCal() string
}
又写了两个结构体Worker和Student
type Worker struct {
    Type int
    Name string
}
type Student struct {
    Name string
}

Implemented a function with the same name as the structure for them respectively

func (w Worker) TypeCal() string {
    if w.Type == 0 {
        return w.Name +"是蓝翔毕业的员工"
    } else {
        return w.Name+"不是蓝翔毕业的员工"
    }
}
func (s Student) TypeCal() string  {
    return s.Name + "还在蓝翔学挖掘机炒菜"
}

Created instances of worker and student respectively

worker := Worker{Type:0, Name:"小华"}
student := Student{Name:"小明"}

Come on, here comes the point. These two instances are placed in the same slice of TypeCalculator

workers := []TypeCalculator{worker, student}

Traverse the slice and call the function in the slice to print the result

for _, v := range workers {
    fmt.Println(v.TypeCal())
}

Simple analysis

From the results, It is true that different instances call their own functions. The function name and return value of this function and the interface are the same. So what if a certain instance does not implement the functions in the interface? When I comment out the function corresponding to Student and then run the program, the program reports the following error (using my loose English translation, Student does not implement TypeCalculator, and the function/method TypeCal cannot be found)

 Student does not implement TypeCalculator (missing TypeCal method)

The above is the detailed content of What is interface in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:studygolang.com. If there is any infringement, please contact admin@php.cn delete