把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口???

实例

  1. // 定义接口
  2. type interface_name interface {
  3. method_name1 [return_type]
  4. method_name2 [return_type]
  5. ...
  6. method_namen [return_type]
  7. }
  1. package main
  2. import "fmt"
  3. type Phone interface {
  4. call()
  5. }
  6. type NokiaPhone struct {
  7. }
  8. func (nokiaPhone NokiaPhone) call() {
  9. fmt.Println("Nokia call you!")
  10. }
  11. type IPhone struct {
  12. }
  13. func (iphone IPhone) call() {
  14. fmt.Println("Iphone call you")
  15. }
  16. func main() {
  17. var phone Phone
  18. phone = new(NokiaPhone)
  19. phone.call()
  20. phone = new(IPhone)
  21. phone.call()
  22. }

例子中定义了一个接口Phone,接口里面有一个方法call()。在main函数里定义了一个Phone类型变量,并分别位置赋值NokiaPhone和IPhone。然后调用call方法,均可输出