Pum*_*eed 3 struct static-typing go
我想创建一个必须使用方法的基本结构,我想在子结构中使用这些方法。例如:
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
}
Run Code Online (Sandbox Code Playgroud)
在新结构中,我想像这样使用它:
type Auth struct {
Base
Username
Password
}
Run Code Online (Sandbox Code Playgroud)
并在主要调用这些方法:
func main() {
a := Auth{
Username: "Test",
Password: "test",
}
a = a.SetType("testtype").(Auth)
j, _ := a.GetJSON()
}
Run Code Online (Sandbox Code Playgroud)
在 SetType 情况下,我因 interface{} 不是Auth类型而出现恐慌,它是Base类型。在 GetJSON 案例中,我得到了一个关于类型的 json,但只有类型。
我想解决的问题有什么解决方案吗?
如评论中所述,嵌入不是继承而是组合,因此您可能必须:
在您所展示的特定情况下(试图GetJSON()还包括外部结构的字段,这是一种不需要太多更改即可使其工作的可能方法(仅在创建时将指向外部结构的指针存储在 Base 中)结构):
package main
import (
"encoding/json"
"fmt"
)
type Base struct {
Type string `json:"$type"`
selfP interface{} // this will store a pointer to the actual sub struct
}
func (b *Base) SetSelfP(p interface{}) {
b.selfP = p
}
func (b *Base) GetJSON() ([]byte, error) {
return json.Marshal(b.selfP)
}
func (b *Base) SetType(typeStr string) {
b.Type = typeStr
}
type Auth struct {
Base
Username string
Password string
}
func main() {
a := &Auth{
Username: "Test",
Password: "test",
}
a.SetSelfP(a) // this line does the trick
a.SetType("testtype")
j, _ := a.GetJSON()
fmt.Println(string(j))
}
Run Code Online (Sandbox Code Playgroud)
游乐场链接:https : //play.golang.org/p/npuy6XMk_t