Questo programma non viene compilato:tipo impossibile caso interruttore
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
}
}
L'errore è:
prog.go:19: impossible type switch case: test() (type error) cannot have dynamic type Validator (missing Error method)
Ma Validator
struttura ha metodo Error
.
Avete qualche consiglio su quando per definire un metodo su un puntatore a oggetto o l'oggetto stesso ? – warvariuc
Definire il metodo su un puntatore quando 1. è necessario modificare l'oggetto. 2. È un grosso oggetto e copiarlo è costoso. – OneOfOne
In questo caso, Validator ha una dimensione pari a 0, quindi è chiaramente meglio usarlo rispetto a un puntatore. –