zoukankan      html  css  js  c++  java
  • Go-23-接口

    接口定义

    type 接口名 interface{
      方法1(参数列表)  [返回值]
      方法2(参数列表)[返回值]
    }

    接口实现

    func (变量 结构体类型)方法1 ([参数列表])(返回值){
    }
    
    func (变量 结构体类型)方法2([参数列表])(返回值){
    }
    package main
    
    import (
        "fmt"
    
    )
    
    //接口的定义与实现
    type Hello interface {
        hello()
    }
    type Cat struct {
    
    }
    type Dog struct {
    
    }
    
    func (c Cat)hello()  {
        fmt.Println("喵~喵~")
    }
    func (d Dog)hello()  {
        fmt.Println("汪~汪~")
    }
    func main() {
        var hello Hello
        hello = Cat{}
        hello.hello()
        hello = Dog{}
        hello.hello()
    }

    duck typing

    Go没有implements或extends关键字,这类编程语言叫作duck typing编程语言。

    package main
    
    import "fmt"
    
    //多态
    type Income interface {
        calculate() float64
        source() string
    }
    // 固定账单项目
    type FixedBinding struct {
        name string
        amount float64
    }
    // 其他
    type Other struct {
        name string
        amount float64
    }
    func (f FixedBinding) calculate() float64{
        return f.amount
    }
    func (f FixedBinding) source() string  {
        return f.name
    }
    func (o Other) calculate() float64{
        return o.amount
    }
    func (o Other) source() string  {
        return o.name
    }
    func main() {
        f1:=FixedBinding{"project1",1111}
        f2:=FixedBinding{"project2",2222}
        o1:=Other{"other1",3333}
        o2:=Other{"other2",4444}
        fmt.Println("f1:",f1.source(),f1.calculate())
        fmt.Println("f2:",f2.source(),f2.calculate())
        fmt.Println("o1:",o1.source(),o1.calculate())
        fmt.Println("o2:",o2.source(),o2.calculate())
        
    }

    空接口:

    空接口中没有任何方法。任意类型都可以实现该接口。空接口这样定义:interface{},也就是包含0个方法(method)的interface。空接口可表示任意数据类型,类似于Java中的object。

    空接口使用场景:

    •  println的参数就是空接口。
    • 定义一个map:key是string,value是任意数据类型。
    • 定义一个切片,其中存储任意类型的数据。
    package main
    
    import "fmt"
    
    //空接口
    
    type I interface{
    }
    func main() {
        // map的key是string,value是任意类型
        map1:=make(map[string]interface{})
        map1["name"]="玫瑰"
        map1["color"]= ""
        map1["num"]=22
        // 切片是任意类型
        sli:=make([]interface{},2,2)
        fmt.Println(sli)
    }

     接口对象转型

    instance,ok:=接口对象.(实际类型)
  • 相关阅读:
    [原][GIS]ARCGIS投影坐标系转换
    [转][osg]探索未知种族之osg类生物【目录】
    [转][osg]探究osg中的程序设计模式【目录】
    [原][资料整理][osg]osgDB文件读取插件,工作机制,支持格式,自定义插件
    [原][landcover]全球地表植被样例图片
    [转]arcgis for server 10.2 下载及安装
    [原]DOM、DEM、landcover,从tms服务发布格式转arcgis、google服务发布格式
    MySQL 数据库最优化设计原则
    MySQL常用存储引擎及如何选择
    Xtrabackup实现Mysql的InnoDB引擎热备份
  • 原文地址:https://www.cnblogs.com/shix0909/p/12991900.html
Copyright © 2011-2022 走看看