加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang语法总结(二十二):接口interface

发布时间:2020-12-16 18:33:56 所属栏目:大数据 来源:网络整理
导读:类型关键字为interface 不需要显式声明实现某个接口,只要实现相关方法就实现了接口 基本示例: type Person interface { Name () string } type Student struct name func ( s Student ) Name string return s . name func main var p Person p = Student :
  • 类型关键字为interface
  • 不需要显式声明实现某个接口,只要实现相关方法就实现了接口
基本示例:
   
   
type Person interface { Name()string}type Studentstruct name func (s Student)Namestringreturn s.namefunc mainvar p Person p = Student:"roc" fmt.Printlnp.Name()) //roc}
  • 接口也可以组合(相当于继承)
  • 可以试探是否为某个struct或interface的实例(ok pattern),相当于Java中的instanceof
    
    
type Teacher Person//接口组合 Teach()type MyTeacherclasst MyTeacher t)Teach("I am teaching ",t.class)func say_hellop Person)if mok := p.(MyTeacher);//看此Person是否为MyTeacher的实例,如果是再执行if内的内容"hello "m} t Teacher MyTeacher name : "english"//roc.Teach//I am teaching english say_hello//hello roc}
  • 可以使用匿名接口
     
     
a interface}

  • 空接口可以看作是所有struct都实现了的。匿名空接口直接写成:interface{}
  • type switch可以判断某变量是哪种类型,并根据不同类型作不同处理
  
      
type A type B b m {})switch t .(type//type switch的关键case Aa Bbdefault"nobody" a "a" b "b"//hello a//hello b}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读