- Pointer variable can call function with pointer or type receiver.Value content variable can call function with pointer receiver or value receiverInterface value content variable CAN NOT call function with pointer
package main
import (
"fmt"
)
func main() {
var a A
var b B = B("BB")
b.a() // It is legal because compiler will take b's address to call func (b *B) a()
// But variable a is no lucky, there is no such sugar, so a can't be assigned to b
// Because a is a value, not a pointer. value variable can't call a function declared for pointer
// a = b // compile error! because there is no a() implementation for value in B
var bp *B = &b
a = bp // OK! There is an a() implementation for pointer in B, so ok
a.a()
var c C = C("CC")
a = c // OK! There is an a() implementation for value in C
a.a()
var cp *C = &c
a = cp // OK! Because a function defined with value type, no matter pointer or value type can call it
a.a()
a = nil
fmt.Println(a)
}
type C string
func (c C) a() {
fmt.Println("c.a")
}
type B string
func (b *B) a() {
fmt.Println("b.a")
}
type A interface {
a()
}
沒有留言:
張貼留言