go 接口

 

1.

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!

 

2.

package main

import (
    "fmt"
)

type Man interface {
    name() string
    age() int
}
type Woman struct {
}

func (woman Woman) name() string {
    return "Jin Yawei"
}
func (woman Woman) age() int {
    return 23
}

type Men struct {
}

func (men Men) name() string {
    return "liweibin"
}
func (men Men) age() int {
    return 27
}
func main() {
    var man Man
    man = new(Woman)
    fmt.Println(man.name())
    fmt.Println(man.age())
    man = new(Men)
    fmt.Println(man.name())
    fmt.Println(man.age())
}

输出

Jin Yawei
23
liweibin
27

 

 

posted @ 2019-01-29 11:03  anobscureretreat  阅读(116)  评论(0编辑  收藏  举报