go interface 例子

package main

import (
    "fmt"
)

type Human struct {
    name  string
    age   int
    phone string
}

type Student struct {
    Human
    school string
    stuID  int
}

type Employee struct {
    Human
    workname string
    worktime int
}

func (h Human) RunAndGo() {
    fmt.Printf("name:%s phone:%s run and go\n", h.name, h.phone)
}

func (e Employee) RunAndGo() {
    fmt.Printf("RunAndGo work name:%s writecode\n", e.workname)
}

func (e Employee) Work(writecode string) {
    fmt.Printf("work name:%s writecode:%s\n", e.workname, writecode)
}

type Men interface {
    RunAndGo()
    //Work(writecode string)
}

func main() {
    m := Student{Human{"mary", 22, "130546587"}, "beijingdaxue", 123456}
    m.RunAndGo()

    w := Employee{Human{"xiaoli", 25, "150123456"}, "c++ engine", 8}
    w.RunAndGo()
    w.Work("go language")

    x := make([]Men, 2)
    x[0], x[1] = m, w //这2个都是不同类型的元素,但是他们实现了interface同一个接口

    for _, value := range x {
        value.RunAndGo()
    }
}

运行:
go run testInterface.go
结果:

name:mary phone:130546587 run and go
RunAndGo work name:c++ engine writecode
work name:c++ engine writecode:go language
name:mary phone:130546587 run and go
RunAndGo work name:c++ engine writecode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值