golang: 轉型成interface時顯示錯誤typeA does not implement interfaceA(Call method has pointer receiver)

constructor回傳value而非pointer時,轉型成interface時顯示錯誤typeA does not implement interfaceA(Call method has pointer receiver)

修改別人寫的代碼時出現一個奇怪的錯誤, 模擬代碼如下:

package main

import "fmt"

func main(){
	phone:= NewPhone("Tom")
	var caller PhoneFeatures = phone
	caller.Call()
}

type Phone struct{
	UserName string
}

func NewPhone(userName string) Phone {
	return Phone{UserName: userName}
}

func (p *Phone) Call()  {
    fmt.Println(p.UserName," Call...")
}

type PhoneFeatures interface{
	Call()
}


執行以上程式碼在轉型成interface時會出現錯誤:

乍看之下很奇怪,Call方法已經有被實現,卻跳出錯誤沒有被實現
而修復的方式有兩種:

  1. 將constructor回傳value改為pointer
    func NewPhone(userName string) *Phone {
    	return &Phone{UserName: userName}
    }

     

  2. 或改利用value receiver實現Call()
    func (p Phone) Call()  {
        fmt.Println(p.UserName," Call...")
    }

     

這時候進一步的疑問就來了,如果constructor回傳pointer搭配value實現interface,結果會是甚麼?

func NewPhone(userName string) *Phone {
	return &Phone{UserName: userName}
}

func (p Phone) Call()  {
    fmt.Println(p.UserName," Call...")
}

修改後執行一切正常,小結如下:

             implementing interface By
             value receiver pointer receiver
constructor returns values ok error
constructor returns pointers ok ok

所以constructor還是返回pointer吧~