第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

是否可以在 Go 函數(shù)中返回結(jié)構(gòu)的動(dòng)態(tài)數(shù)組?

是否可以在 Go 函數(shù)中返回結(jié)構(gòu)的動(dòng)態(tài)數(shù)組?

Go
www說(shuō) 2022-04-20 17:30:39
顯然,我想根據(jù)函數(shù)參數(shù)(getOccupationStructs 函數(shù))返回一個(gè)結(jié)構(gòu)數(shù)組,以保持 DRY (不在所有其他函數(shù)中使用 if else ),但這似乎不可能,所以這是我的錯(cuò)誤: 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)    }}是否有任何有效的解決方法來(lái)解決這個(gè)問(wèn)題?
查看完整描述

1 回答

?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊

Go 沒(méi)有結(jié)構(gòu)子類型,因此要獲得多態(tài)性,您需要使用接口。

定義一個(gè)所有結(jié)構(gòu)類型都實(shí)現(xiàn)的接口,它甚至可以是私有的,比如interface embedsHuman { Name() string },然后返回[]embedsHuman。

或者,重構(gòu)你的模式或僅將它的 Go 表示重構(gòu)為層次較少的東西(也許人類可以有很多角色?),這樣它就不會(huì)與 Go 的類型系統(tǒng)發(fā)生沖突。


查看完整回答
反對(duì) 回復(fù) 2022-04-20
  • 1 回答
  • 0 關(guān)注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)