为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以在 Go 函数中返回结构的动态数组?

是否可以在 Go 函数中返回结构的动态数组?

Go
www说 2022-04-20 17:30:39
显然,我想根据函数参数(getOccupationStructs 函数)返回一个结构数组,以保持 DRY (不在所有其他函数中使用 if else ),但这似乎不可能,所以这是我的错误: cannot use []Student literal (type []Student) as type []struct {} in   return argument cannot use []Employee literal (type []Employee ) as type []struct {} in   return argument这是我的代码:package mainimport (    "fmt"    "time"    "github.com/jinzhu/gorm"    _ "github.com/jinzhu/gorm/dialects/postgres")type Human struct {    ID          uint        `gorm:"primary_key" gorm:"column:_id" json:"_id"`    Name        string      `gorm:"column:name" json:"name"`    Age         int         `gorm:"column:age" json:"age"`    Phone       string      `gorm:"column:phone" json:"phone"`}type Student struct {    Human     School      string      `gorm:"column:school" json:"school"`    Loan        float32     `gorm:"column:loan" json:"loan"`}type Employee struct {    Human     Company     string      `gorm:"column:company" json:"company"`    Money       float32     `gorm:"column:money" json:"money"`}func getOccupationStructs(occupation string) []struct{} {    switch occupation {        case "student":            return []main.Student{}        case "employee":            return []main.Employee{}        default:            return []main.Student{}    }}func firstFunction(){    m := getOccupationStructs("student")    for _, value := range m{        fmt.Println("Hi, my name is "+value.Name+" and my school is "+value.School)    }}func secondFunction(){    m := getOccupationStructs("employee")    for _, value := range m{        fmt.Println("Hi, my name is "+value.Name+" and my company is "+value.Company)    }}是否有任何有效的解决方法来解决这个问题?
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

Go 没有结构子类型,因此要获得多态性,您需要使用接口。

定义一个所有结构类型都实现的接口,它甚至可以是私有的,比如interface embedsHuman { Name() string },然后返回[]embedsHuman

或者,重构你的模式或仅将它的 Go 表示重构为层次较少的东西(也许人类可以有很多角色?),这样它就不会与 Go 的类型系统发生冲突。


查看完整回答
反对 回复 2022-04-20
  • 1 回答
  • 0 关注
  • 189 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号