Go - Interface Satisfaction - 3


  • Pointer variable can call function with pointer or type receiver.
    Value content variable can call function with pointer receiver or value receiver
    Interface 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()
}

沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...