如何获得父嵌入式结构字段值? [英] How to get parent embedded struct field value?
问题描述
类型动态结构{
Id字符串
//和一些更常见的字段
}
使用我的软件包的用户应该能够实现自己的 Animal
s。由于我需要 Id
在我的一个方法中用户必须嵌入我的结构。
type Dog struct {
Animal
Name string
Legs int
}
在我的包中,我有一个 save()
函数,可以将 Animal
s保存为数据库。因为我不知道用户的类型,我必须使用 interface {}
作为参数类型。我的问题是:如何获得 Id
(来自父级结构 Animal
)?目前我使用一些JSON解析和解组,但这是去/去的路吗?
func put(doc接口{})错误{
res,err:= json.Marshal(doc)
if err!= nil {
return err
}
var animal * Animal
err = json.Unmarshal(res,& animal)
if err!= nil {
return err
}
fmt.Println(animal.Id)//终于有了Id
// ...
}
用法
func main(){
bello:=狗{
Animal:Animal {
Id :abcd1234,
},
名称:bello,
Legs:4,
}
err:= put(bello)
/ / ...
}
可以添加一个接口以确保获得对父结构的引用:
type AnimalGetter interface {
GetAnimal()* Animal
}
func(dog * Dog)GetAnimal()* Animal {
return& dog.Animal
}
这样可以保存方法做一个类型断言(AnimalGetter): 查看中的完整示例 play.golang.org 输出: 简单: p> ( play.golang.org ) I have the following struct in my package. A user who uses my package should be able to implement own In my package I have a Usage
Maybe you can add an interface in order to be sure to get a reference to the parent struct: That would allow your save method to do a type assertion (AnimalGetter): See a complete example in play.golang.org. Output: Simpler: 这篇关于如何获得父嵌入式结构字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ p $
animal:= obj。(AnimalGetter)
fmt.Printf(%v\\\
,animal.GetAnimal())
}
& ; {{dogid} wouf 0}
& {dogid}
func save(animal AnimalGetter){
fmt.Printf(%v \\\
,animal.GetAnimal() )
}
type Animal struct {
Id string
// and some more common fields
}
Animal
s. As I need Id
in one of my methods the user has to embed my struct.type Dog struct {
Animal
Name string
Legs int
}
save()
function that saves Animal
s to database. As I don't know the user's type I have to use interface{}
as argument type. My question is: How do I get the Id
(from the parent struct Animal
)? At the moment I use some JSON parsing and unmarshalling, but is this the way to go/Go?func put(doc interface{}) error {
res, err := json.Marshal(doc)
if err != nil {
return err
}
var animal *Animal
err = json.Unmarshal(res, &animal)
if err != nil {
return err
}
fmt.Println(animal.Id) // finally I have the Id
// ...
}
func main() {
bello := Dog{
Animal: Animal{
Id: "abcd1234",
},
Name: "bello",
Legs: 4,
}
err := put(bello)
// ...
}
type AnimalGetter interface {
GetAnimal() *Animal
}
func (dog *Dog) GetAnimal() *Animal {
return &dog.Animal
}
func save(obj interface{}) {
animal := obj.(AnimalGetter)
fmt.Printf("%v\n", animal.GetAnimal())
}
&{{dogid} wouf 0}
&{dogid}
func save(animal AnimalGetter) {
fmt.Printf("%v\n", animal.GetAnimal())
}