I would like to create a base struct which have to method, I want to use these methods in the substructs. For example:
type Base struct {
Type string `json:"$type"`
}
func (b Base) GetJSON() ([]byte, error) {
return json.Marshal(b)
}
func (b Base) SetType(typeStr string) interface{} {
b.Type = typeStr
return b
}
In the new struct I want to use it like this:
type Auth struct {
Base
Username
Password
}
and call these methods in the main:
func main() {
a := Auth{
Username: "Test",
Password: "test",
}
a = a.SetType("testtype").(Auth)
j, _ := a.GetJSON()
}
In the SetType case I got a panic caused by interface{} is not Auth
type, it is Base
type.
In the GetJSON case I got a json about the Type, but only the Type.
Is there any solution for the problem what I want to solve?
return b.Type = typeStr
isn't a valid Go statement. Base isn't going to haveUsername
andPassword
fields if that's what you're trying to do. There is no inheritance in Go. – Subsonic