在子结构中定义方法的 Golang 基础结构
Golang base struct to define methods in substructs
我想创建一个必须有方法的基础结构,我想在子结构中使用这些方法。例如:
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
}
在新结构中我想这样使用它:
type Auth struct {
Base
Username
Password
}
并在主函数中调用这些方法:
func main() {
a := Auth{
Username: "Test",
Password: "test",
}
a = a.SetType("testtype").(Auth)
j, _ := a.GetJSON()
}
在 SetType 的情况下,由于 interface{} 不是 Auth
类型,它是 Base
类型,我得到了一个恐慌。
在 GetJSON 案例中,我得到了关于类型的 json,但只有类型。
我想解决的问题有解决方案吗?
如评论中所述,嵌入不是继承而是组合,因此您可能必须:
- 重新考虑您的设计以使用 Go 可用的工具
- 通过广泛的黑客攻击来获得你想要的结果
在您展示的特定情况下(试图让 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))
}
我想创建一个必须有方法的基础结构,我想在子结构中使用这些方法。例如:
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
}
在新结构中我想这样使用它:
type Auth struct {
Base
Username
Password
}
并在主函数中调用这些方法:
func main() {
a := Auth{
Username: "Test",
Password: "test",
}
a = a.SetType("testtype").(Auth)
j, _ := a.GetJSON()
}
在 SetType 的情况下,由于 interface{} 不是 Auth
类型,它是 Base
类型,我得到了一个恐慌。
在 GetJSON 案例中,我得到了关于类型的 json,但只有类型。
我想解决的问题有解决方案吗?
如评论中所述,嵌入不是继承而是组合,因此您可能必须:
- 重新考虑您的设计以使用 Go 可用的工具
- 通过广泛的黑客攻击来获得你想要的结果
在您展示的特定情况下(试图让 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))
}