设为首页收藏本站
网站公告 | 这是第一条公告
     

 找回密码
 立即注册
缓存时间17 现在时间17 缓存数据 这个世界上很多东西会变,很多人会走。 但你在我心里,从开始的那一天,到现在从来没有变过。 我一直在等,等你的消息。

这个世界上很多东西会变,很多人会走。 但你在我心里,从开始的那一天,到现在从来没有变过。 我一直在等,等你的消息。 -- 盛夏的果实

查看: 894|回复: 4

详解Golang语言中的interface

[复制链接]

  离线 

TA的专栏

  • 打卡等级:热心大叔
  • 打卡总天数:223
  • 打卡月天数:0
  • 打卡总奖励:3336
  • 最近打卡:2025-04-17 02:43:34
等级头衔

等級:晓枫资讯-上等兵

在线时间
0 小时

积分成就
威望
0
贡献
403
主题
390
精华
0
金钱
4581
积分
846
注册时间
2023-1-5
最后登录
2025-5-31

发表于 2023-8-8 13:07:04 来自手机 | 显示全部楼层 |阅读模式
interface是一组method签名的组合,interface可以被任意对象实现,一个对象也可以实现多个interface。任意类型都实现了空interface(也就是包含0个method的interface),空interface可以存储任意类型的值。interface定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。
go version go1.12
  1. package main

  2. import (
  3.   "fmt"
  4. )

  5. // 定义struct
  6. type Human struct {
  7.   name string
  8.   age  int
  9.   phone string
  10. }
  11. type Student struct {
  12.   Human // 匿名字段
  13.   school string
  14.   loan  float32
  15. }
  16. type Employee struct {
  17.   Human  // 匿名字段
  18.   company string
  19.   money  float32
  20. }

  21. // Human对象实现SayHi()方法
  22. func (h Human) SayHi() {
  23.   fmt.Printf("Hi, I am %s, you can call me on %s\n", h.name, h.phone)
  24. }

  25. // Human对象实现Sing()方法
  26. func (h Human) Sing(lyrics string) {
  27.   fmt.Println("La la la...", lyrics)
  28. }

  29. // Human对象实现Guzzle()方法
  30. func (h Human) Guzzle(beerStein string) {
  31.   fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
  32. }

  33. // Employee对象重写SayHi()方法
  34. func (e Employee) SayHi() {
  35.   fmt.Printf("Hi I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone)
  36. }

  37. // Student对象实现BorrowMoney()方法
  38. func (s Student) BorrowMoney(amount float32) {
  39.   s.loan += amount
  40. }

  41. // Employee对象实现SpendSalary()方法
  42. func (e Employee) SpendSalary(amount float32) {
  43.   e.money -= amount
  44. }

  45. // 定义interface,interface是一组method签名的组合
  46. // interface可以被任意对象实现,一个对象也可以实现多个interface
  47. // 任意类型都实现了空interface(也就是包含0个method的interface)
  48. // 空interface可以存储任意类型的值
  49. // interface Men的3个method被Human,Student,Employee实现,也就是这3个对象都实现了interface Men。即:
  50. // interface定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。
  51. type Men interface {
  52.   SayHi()
  53.   Sing(lyrice string)
  54.   Guzzle(beerStein string)
  55. }

  56. // interface YoungChap的BorrowMoney() method只被Student对象实现,也就是只有Student实现了YoungChap
  57. type YoungChap interface {
  58.   SayHi()
  59.   Sing(song string)
  60.   BorrowMoney(amount float32)
  61. }

  62. // interface ElderlyGent的SpendSalary() method只被Employee对象实现,也就是只有Employee实现了ElderlyGent
  63. type ElderlyGent interface {
  64.   SayHi()
  65.   Sing(song string)
  66.   SpendSalary(amount float32)
  67. }

  68. func main() {
  69.   // 定义Student类型的变量
  70.   lucy := Student{Human{"lucy", 19, "10086"}, "tsinghua", 100.00}
  71.   lily := Student{Human{"lily", 19, "10086"}, "tsinghua", 100.00}
  72.   liming := Student{Human{"liming", 19, "10086"}, "tsinghua", 100.00}
  73.   // 定义Employee类型的变量
  74.   tom := Employee{Human{"tom", 29, "10000"}, "Google", 200.00}
  75.   // 定义Men类型的变量i
  76.   var i Men
  77.   // i存储Student
  78.   i = lucy
  79.   fmt.Println("This is lucy, a student:")
  80.   i.SayHi()
  81.   i.Sing("Happy Birthday")
  82.   i.Guzzle("Ha ha ha...")

  83.   // i存储Employee
  84.   i = tom
  85.   fmt.Println("This is tom, an Employee:")
  86.   i.SayHi()

  87.   // 定义slice Men,包含Men类型元素的切片,这个slice可以被赋予实现了Men接口的任意结构的对象
  88.   fmt.Println("Let's use a slice of Men and see what happens:")
  89.   x := make([]Men, 3)
  90.   // 三个不同类型(不同Method)的元素,实现了同一个interface(Men)
  91.   x[0], x[1], x[2] = lucy, lily, liming
  92.   for _, value := range x {
  93.     value.SayHi()
  94.   }
  95. }
复制代码
函数参数
interface接口还可以作为函数参数,因为interface的变量可以持有任意实现该interface类型的对象,我们可以通过定义interface参数,让函数接受各种类型的参数。 判断interface变量存储的元素的类型,目前常用的有两种方法:Comma-ok断言和switch测试。
go version go1.12
  1. /**
  2. * interface接口作为函数参数
  3. * 判断interface变量存储的元素的类型
  4. */
  5. package main

  6. import (
  7.   "fmt"
  8.   "strconv"
  9. )

  10. // 定义Human对象
  11. type Human struct {
  12.   name string
  13.   age  int
  14.   phone string
  15. }

  16. // 定义空接口
  17. type Element interface{}

  18. // 定义切片
  19. type List []Element

  20. // 定义Person对象
  21. type Person struct {
  22.   name string
  23.   age int
  24. }

  25. // 通过定义interface参数,让函数接受各种类型的参数
  26. // 通过这个Method(方法),Human对象实现了fmt.Stringer接口
  27. // Stringer接口是fmt.Println()的参数,最终使得Human对象可以作为fmt.Println的参数被调用
  28. func (h Human) String() string {
  29.   return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">"
  30. }

  31. // 通过定义interface参数,让函数接受各种类型的参数
  32. // 通过这个Method(方法),Person对象实现了fmt.Stringer接口
  33. // Stringer接口是fmt.Println()的参数,最终使得Person对象可以作为fmt.Println的参数被调用
  34. func (p Person) String() string {
  35.   return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
  36. }

  37. func main() {
  38.   // interface作为函数的参数传递
  39.   Lucy := Human{"Lucy", 29, "10086"}
  40.   fmt.Println("This human is:", Lucy)

  41.   list := make(List, 3)
  42.   list[0] = 100
  43.   list[1] = "Hello Golang!"
  44.   list[2] = Person{"Lily", 19}

  45.   // Comma-ok断言
  46.   for index, element := range list {
  47.     // 判断变量的类型 格式:value, ok = element(T)
  48.     // value是interface变量的值,ok是bool类型,element是interface的变量,T是断言的interface变量的类型
  49.     if value, ok := element.(int); ok {
  50.       fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
  51.     } else if value, ok := element.(string); ok {
  52.       fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
  53.     } else if value, ok := element.(Person); ok {
  54.       fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
  55.     } else {
  56.       fmt.Printf("list[%d] is a different type\n", index)
  57.     }
  58.   }

  59.   // switch
  60.   for index, element := range list {
  61.     // 注意:element.(type)语法不能在switch外的任何逻辑中使用
  62.     switch value := element.(type) {
  63.     case int:
  64.       fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
  65.     case string:
  66.       fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
  67.     case Person:
  68.       fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
  69.     default:
  70.       fmt.Printf("list[%d] is a differernt type", index)
  71.     }
  72.   }
  73. }
复制代码
以上就是详解Golang语言中的interface的详细内容,更多关于Golang语言中的interface的资料请关注晓枫资讯其它相关文章!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
晓枫资讯-科技资讯社区-免责声明
免责声明:以上内容为本网站转自其它媒体,相关信息仅为传递更多信息之目的,不代表本网观点,亦不代表本网站赞同其观点或证实其内容的真实性。
      1、注册用户在本社区发表、转载的任何作品仅代表其个人观点,不代表本社区认同其观点。
      2、管理员及版主有权在不事先通知或不经作者准许的情况下删除其在本社区所发表的文章。
      3、本社区的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,举报反馈:点击这里给我发消息进行删除处理。
      4、本社区一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
      5、以上声明内容的最终解释权归《晓枫资讯-科技资讯社区》所有。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

  离线 

TA的专栏

等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
0
主题
0
精华
0
金钱
18
积分
16
注册时间
2022-12-24
最后登录
2022-12-24

发表于 2024-1-22 04:24:46 | 显示全部楼层
顶顶更健康!!!
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

  离线 

TA的专栏

  • 打卡等级:即来则安
  • 打卡总天数:19
  • 打卡月天数:0
  • 打卡总奖励:246
  • 最近打卡:2025-03-12 02:46:51
等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
0
主题
0
精华
0
金钱
290
积分
44
注册时间
2023-4-8
最后登录
2025-3-12

发表于 2025-1-19 04:45:05 | 显示全部楼层
路过,支持一下
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

  离线 

TA的专栏

等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
0
主题
0
精华
0
金钱
15
积分
10
注册时间
2022-12-25
最后登录
2022-12-25

发表于 2025-3-20 14:42:57 | 显示全部楼层
感谢楼主,顶。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~

  离线 

TA的专栏

  • 打卡等级:无名新人
  • 打卡总天数:1
  • 打卡月天数:0
  • 打卡总奖励:5
  • 最近打卡:2025-04-09 22:28:57
等级头衔

等級:晓枫资讯-列兵

在线时间
0 小时

积分成就
威望
0
贡献
0
主题
0
精华
0
金钱
17
积分
4
注册时间
2023-11-20
最后登录
2025-4-9

发表于 2025-4-21 16:37:09 | 显示全部楼层
感谢楼主分享。
http://bbs.yzwlo.com 晓枫资讯--游戏IT新闻资讯~~~
严禁发布广告,淫秽、色情、赌博、暴力、凶杀、恐怖、间谍及其他违反国家法律法规的内容。!晓枫资讯-社区
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1楼
2楼
3楼
4楼
5楼

手机版|晓枫资讯--科技资讯社区 本站已运行

CopyRight © 2022-2025 晓枫资讯--科技资讯社区 ( BBS.yzwlo.com ) . All Rights Reserved .

晓枫资讯--科技资讯社区

本站内容由用户自主分享和转载自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。

如有侵权、违反国家法律政策行为,请联系我们,我们会第一时间及时清除和处理! 举报反馈邮箱:点击这里给我发消息

Powered by Discuz! X3.5

快速回复 返回顶部 返回列表