1. 程式人生 > >再看go的interface程式碼示例

再看go的interface程式碼示例

       程式碼:

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

     

       程式碼:

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

      

      程式碼:

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

 

       程式碼:

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)

 

      好好理解下。