zoukankan      html  css  js  c++  java
  • Go语言学习笔记(9)——接口类型

    接口

    Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口

    /* 定义接口 */
    type interface_name interface {
       method_name1 [return_type]
       method_name2 [return_type]
       method_name3 [return_type]
       ...
       method_namen [return_type]
    }
    
    /* 定义结构体 */
    type struct_name struct {
       /* variables */
    }
    
    /* 实现接口方法 */
    func (struct_name_variable struct_name) method_name1() [return_type] {
       /* 方法实现 */
    }
    ...
    func (struct_name_variable struct_name) method_namen() [return_type] {
       /* 方法实现*/
    }



     

    实例 :

    package main
    
    import "fmt"
    
    type Phone interface {
        call()
    }
    
    type NokiaPhone struct {
    }
    
    func (nokiaPhone NokiaPhone) call() {
        fmt.Println("I am Nokia, I can call you!")
    }
    
    type IPhone struct {
    }
    
    func (iPhone IPhone) call() {
        fmt.Println("I am iPhone, I can call you!")
    }
    
    func main() {
        var phone Phone
    
        phone = new(NokiaPhone)
        phone.call()
    
        phone = new(IPhone)
        phone.call()
    
    }
    

      

    打印结果:

          I am Nokia, I can call you!

          I am iPhone, I can call you!

    ///纵有疾风起,人生不言弃///
  • 相关阅读:
    lucene初探
    直接插入排序算法(java)
    快速排序优化算法
    大根堆
    学习资料地址
    Lucene:基于Java的全文检索引擎简介
    开关按钮
    微信小程序—如何获取用户输入文本框的值
    微信小程序—获取用户网络状态和设备的信息
    Bootstrap 导航栏
  • 原文地址:https://www.cnblogs.com/skzxc/p/11244392.html
Copyright © 2011-2022 走看看