,該程序不能編譯:不可能類型開關殼體
package main
type Validator struct {
}
// Error implements error interface
func (v *Validator) Error() string {
return ""
}
func test() error {
return &Validator{}
}
func main() {
switch test().(type) {
case nil:
println("No error")
case Validator:
println("Validation error")
return
default:
println("Unknown error")
return
}
}
錯誤是:
prog.go:19: impossible type switch case: test() (type error) cannot have dynamic type Validator (missing Error method)
但是Validator
結構有方法Error
。
你有沒有關於何時上的指針定義一個方法的任何意見,對象或對象本身? – warvariuc
當你需要修改對象時,在指針上定義方法。 2.這是一個大對象,複製它很昂貴。 – OneOfOne
在這種情況下,Validator的大小爲0,所以使用它比指針更好。 –