gpt4 book ai didi

go - 如何将任何结构作为参数发送给方法并返回结构?

转载 作者:IT王子 更新时间:2023-10-29 02:37:15 27 4
gpt4 key购买 nike

我是 Go 的新手,我想看看是否有一种方法可以接收任何结构作为参数。

我的代码中有类似这样的函数,它对 5 个结构执行完全相同的操作并返回相同的结构,但我不知道我是否可以这样做。我想知道我是否可以做这样的事情:

type Car struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
Windows int `yaml:"Windows"`
}

type Motorcycle struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
}

type Bus struct {
Model string `yaml:"Model"`
Color string `yaml:"Color"`
Wheels int `yaml:Wheels"`
Passengers int `yaml:"Passengers"`
}

func main () {

car := GetYamlData(Car)
motorcycle := GetYamlData(Motorcycle)
Bus := GetYamlData(Bus)
}

func GetYamlData(struct anyStructure) (ReturnAnyStruct struct){

yaml.Unmarshal(yamlFile, &anyStructure)

return anyStructure
}

可以像上面的代码那样做吗?实际上我有的是这样的:

func main(){
car, _, _ := GetYamlData("car")
_,motorcycle,_ := GetYamlData("motorcycle")
_,_,bus := GetYamlData("bus")
}

func GetYamlData(structureType string) (car *Car, motorcycle *Motorcycle, bus *Bus){

switch structureType{

case "car":
yaml.Unmarshal(Filepath, car)
case "motorcycle":
yaml.Unmarshal(Filepath, motorcycle)
case "bus":
yaml.Unmarshal(Filepath, bus)
}

return car, motorcycle, bus

}

随着时间的推移,它会增加,它会返回很多值,我不想要很多返回值,有没有办法用我发布的第一个代码来做到这一点?

最佳答案

您可以采用与 yaml.Unmarshal 完全相同的方式来执行此操作,方法是接收一个值以解码为:

func GetYamlData(i interface{}) {
yaml.Unmarshal(Filepath, i)
}

示例用法:

func main () {
var car Car
var motorcycle Motorcycle
var bus Bus
GetYamlData(&car)
GetYamlData(&motorcycle)
GetYamlData(&bus)
}

关于go - 如何将任何结构作为参数发送给方法并返回结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51482629/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com