您现在的位置是:群英 > 开发技术 > 编程语言
Golang的interface怎么理解,用法是什么
Admin发表于 2022-08-06 17:56:46497 次浏览
今天就跟大家聊聊有关“Golang的interface怎么理解,用法是什么”的内容,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

   

Golang中的interface

先说说接口,接口我理解为一些行为的集合。似乎还是很懵x。来看看代码和允许效果,再说。

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
}

分别为他们实现了一个与结构体中同名的函数

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

分别创建worker和student的实例

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

来来来,重点来了,把这两个实例放同一个TypeCalculator的切片中

workers := []TypeCalculator{worker, student}

遍历这个切片,并调用切片中的函数打印结果

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

简单分析

从结果上看,确实是不同的实例调用的是各自的函数,这个函数和interface中的函数名和返回值是相同的。那么加入要是某个实例没有实现interface中的函数呢?当把Student对应的函数注释掉,然后再运行程序,程序报错如下(用我的散装英语翻译就是,Student 没有实现TypeCalculator,TypeCal这个函数/方法找不到)

 Student does not implement TypeCalculator (missing TypeCal method)

以上就是关于Golang的interface怎么理解,用法是什么的介绍,本文内容仅供参考,有需要的朋友可以借鉴了解看看,希望对大家学习或工作,想要了解更多欢迎关注群英网络,小编每天都会为大家更新不同的知识。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: Golang的interface
相关信息推荐
2022-02-22 18:02:54 
摘要:Python中字典添加元素的方法是什么?Python中,要实现向字典添加元素,我们通过给定键值对直接向字典中添加元素来实现,具体的方法及代码如下,感兴趣的朋友可以参考。
2022-08-13 17:50:43 
摘要:给大家带来一篇关于介绍php fseek函数读取大文件两种方法的相关教程文章,内容涉及到php、fseek、读取大文件、php fseek函数读取大文件两种方法等相关内容,更多关于php fseek函数读取大文件两种方法的内容希望能够帮助到大家。
2022-12-24 11:46:06 
摘要:两种去除方法:1、利用array_splice()函数,只需要将该函数的第二个参数设置为指定下标,第三参数设置为1即可,语法“array_splice($arr, 指定下标,1)”。2、利用“$数组名[下标]”语句和unset()函数,语法“unset($arr[指定下标])”。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部