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:=接口对象.(实际类型)

 

posted @ 2020-05-30 12:21  sixinshuier  阅读(141)  评论(0编辑  收藏  举报