假设我有这段代码:
type Type1 struct {
Name string `json:"name,omitempty"`
Path string `json:"path"`
File string `json:"file"`
Tag int `json:"tag"`
Num int `json:"num"`
}
func LoadConfiguration(data []byte) (*Type1, error) {
config, err := loadConf1(data)
if err != nil {
return nil, err
}
confOther, err := loadConfOther1()
if err != nil {
return nil, err
}
// do something with confOther
fmt.Println("confOther", confOther)
if confOther.Tag == 0 {
config.Num = 5
}
// do something with config attributes of type1
if config.Tag == 0 {
config.Tag = 5
}
if config.Num == 0 {
config.Num = 4
}
return config, nil
}
func loadConf1(bytes []byte) (*Type1, error) {
config := &Type1{}
if err := json.Unmarshal(bytes, config); err != nil {
return nil, fmt.Errorf("cannot load config: %v", err)
}
return config, nil
}
func loadConfOther1() (*Type1, error) {
// return value of this specific type
flatconfig := &Type1{}
// read a file as []byte
// written as a fixed array to simplify this example
fileContent := []byte{10, 22, 33, 44, 55}
if err := json.Unmarshal(fileContent, flatconfig); err != nil {
return nil, fmt.Errorf("cannot read config %v", err)
}
return flatconfig, nil
}
唯一的公共功能是LoadConfiguration。
它基于真实代码,用于读取 json 数据作为特定结构。如果某些东西看起来没用,那是因为我简化了原始代码。
上面的代码没问题,但现在我想创建另一个名为“Type2”的结构类型,并重新使用相同的方法将数据读入 Type2 而无需复制和粘贴所有内容。
type Type2 struct {
Name string `json:"name,omitempty"`
Path string `json:"path"`
Map *map[string]interface{} `json:"map"`
Other string `json:"other"`
}
基本上,我希望能够调用LoadConfigurationType2。我可以接受调用特定方法,例如LoadConfiguration2,但我也不想复制和粘贴loadConf1和 loadConfOther1。有没有办法在 Go 1.18 中以惯用的方式做到这一点?
神不在的星期二
相关分类