您的位置:首页 > 编程语言

再看go的interface代码示例

2018-11-09 22:06 267 查看
版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/83506568

       代码:

[code]package main
import "fmt"

type Base interface {
Input() int
}

type Dog struct {
}

func (p Dog) Input() int {
fmt.Println("call input dog")
return 100
}

func main() {
handler := func() Base { return Dog{} }
fmt.Printf("type: %T, %v\n", handler(), handler().Input())
}

        结果:

call input dog
type: main.Dog, 100

     

       代码:

[code]package main
import "fmt"

type Base interface {
Input() int
}

type Dog struct {
}

func (p Dog) Input() int {
fmt.Println("call input dog")
return 100
}

func main() {
handler := func() Base { return &Dog{} }
fmt.Printf("type: %T, %v\n", handler(), handler().Input())
}

       结果:

call input dog
type: *main.Dog, 100

      

      代码:

[code]package main
import "fmt"

type Base interface {
Input() int
}

type Dog struct {
}

func (p *Dog) Input() int {
fmt.Println("call input dog")
return 100
}

func main() {
handler := func() Base { return &Dog{} }
fmt.Printf("type: %T, %v\n", handler(), handler().Input())
}

       结果:

call input dog
type: *main.Dog, 100

 

       代码:

[code]package main
import "fmt"

type Base interface {
Input() int
}

type Dog struct {
}

func (p *Dog) Input() int {
fmt.Println("call input dog")
return 100
}

func main() {
handler := func() Base { return Dog{} }
fmt.Printf("type: %T, %v\n", handler(), handler().Input())
}

       结果:

# command-line-arguments
./a.go:17:40: cannot use Dog literal (type Dog) as type Base in return argument:
        Dog does not implement Base (Input method has pointer receiver)

 

      好好理解下。

 

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: