美文网首页
什么是Go语言中的interface

什么是Go语言中的interface

作者: louyang | 来源:发表于2021-06-21 17:52 被阅读0次

Interface(接口)在Go语言中就是一系列的函数原型(function signature),例如:

type person interface {
    SayHello()
}

每个实现person接口的数据结构,如学生,老师,都会SayHello()。

例如:

package main

import (
    "log"
)

type person interface {
    SayHello()
}

type Student struct {
}

func (s Student) SayHello() {
    log.Print("Hello, I am a student.")
}

func main() {
    var p person
    p = Student{}
    p.SayHello();
}

运行结果:

2021/06/21 12:41:21 Hello, I am a student.

参考

https://zetcode.com/golang/interface/

相关文章

网友评论

      本文标题:什么是Go语言中的interface

      本文链接:https://www.haomeiwen.com/subject/arayyltx.html