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

前端之家收集整理的这篇文章主要介绍了golang语法总结(二十二):接口interface前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  • 类型关键字为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}
原文链接:https://www.f2er.com/go/189928.html

猜你在找的Go相关文章