顯然,我想根據(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)題?
是否可以在 Go 函數(shù)中返回結(jié)構(gòu)的動(dòng)態(tài)數(shù)組?
www說(shuō)
2022-04-20 17:30:39