我实现了一个接口Fruit及其两个实现:Apple和Banana。
我想从 yaml 文件加载数据到两个实现的对象中:
capacity: 4
Apple:
- name: "apple1"
number: 1
- name: "apple2"
number: 1
Banana:
- name: "banana1"
number: 2
我实现了UnmarshalYaml将数据加载到对象中的接口:
package main
import (
"errors"
"gopkg.in/yaml.v3"
"log"
"fmt"
)
type FruitBasket struct {
Capacity int `yaml:"capacity"`
Fruits []Fruit
}
func NewFruitBasket() *FruitBasket {
fb := new(FruitBasket)
return fb
}
type Fruit interface {
GetFruitName() string
GetNumber() int
}
type Apple struct {
Name string `yaml:"name"`
Number int `yaml:"number"`
}
type Banana struct {
Name string `yaml:"name"`
Number int `yaml:"number"`
}
func (apple *Apple) GetFruitName() string {
return apple.Name
}
func (apple *Apple) GetNumber() int {
return apple.Number
}
func (banana *Banana) GetFruitName() string {
return banana.Name
}
func (banana *Banana) GetNumber() int {
return banana.Number
}
type tmpFruitBasket struct {
Capacity int `yaml:"capacity"`
Fruits []map[string]yaml.Node
}
func (fruitBasket *FruitBasket) UnmarshalYAML(value *yaml.Node) error {
var tmpFruitBasket tmpFruitBasket
if err := value.Decode(&tmpFruitBasket); err != nil {
return err
}
fruitBasket.Capacity = tmpFruitBasket.Capacity
fruits := make([]Fruit, 0, len(tmpFruitBasket.Fruits))
for i := 0; i < len(tmpFruitBasket.Fruits); i++ {
for tag, node := range tmpFruitBasket.Fruits[i] {
switch tag {
case "Apple":
apple := &Apple{}
if err := node.Decode(apple); err != nil {
return err
}
fruits = append(fruits, apple)
case "Banana":
banana := &Banana{}
if err := node.Decode(banana); err != nil {
return err
然而,这是行不通的。似乎Apple和Banana标签的数据未加载。Fruits可能是因为我的结构中缺少切片的 yaml 标志tmpFruitBasket。但是,作为Fruit一个接口,我无法定义 yaml 标志。将来,我想实现代表具体水果(例如草莓)的其他结构,实现该接口Fruit。
关于如何解决这个问题有什么想法吗?
Smart猫小萌
相关分类