mam ten przykładowy kodmetoda Golang ze wskaźnikiem odbiornika
package main
import (
"fmt"
)
type IFace interface {
SetSomeField(newValue string)
GetSomeField() string
}
type Implementation struct {
someField string
}
func (i Implementation) GetSomeField() string {
return i.someField
}
func (i Implementation) SetSomeField(newValue string) {
i.someField = newValue
}
func Create() IFace {
obj := Implementation{someField: "Hello"}
return obj // <= Offending line
}
func main() {
a := Create()
a.SetSomeField("World")
fmt.Println(a.GetSomeField())
}
SetSomeField
nie działa zgodnie z oczekiwaniami, ponieważ jego odbiornik nie jest typu wskaźnika.
Gdybym zmienić metodę do odbiornika wskaźnik, co by się spodziewać do pracy, wygląda to tak:
func (i *Implementation) SetSomeField(newValue string) { ...
Kompilacja prowadzi do następującego błędu:
prog.go:26: cannot use obj (type Implementation) as type IFace in return argument:
Implementation does not implement IFace (GetSomeField method has pointer receiver)
Jak można Mam struct
implementować interfejs i zmienić wartość rzeczywistej instancji bez tworzenia kopii?
Oto hackable urywek: https://play.golang.org/p/ghW0mk0IuU
Już widziałem to pytanie In go (golang), how can you cast an interface pointer into a struct pointer?, ale nie mogę zobaczyć, jak to jest związane z tym przykładzie.
Obie metody wymagają odbiorniki wskaźnik, jeszcze jesteś tylko wdrożenie część interfejsu. – elithrar