【问题标题】:Is it possible to return dynamic array of struct in Go function?是否可以在 Go 函数中返回结构的动态数组?
【发布时间】:2016-11-10 05:36:03
【问题描述】:

显然,我想根据函数参数(getOc​​cupationStructs 函数)返回一个结构数组,以保持 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 main

import (
    "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)
    }
}

是否有任何有效的解决方法来解决这个问题?

【问题讨论】:

  • 您遇到了什么错误?
  • @Nadh 我已经将它添加到问题中,谢谢提醒我
  • 正如@nothingmuch 在答案中指出的那样,Go 没有结构子类型。它也没有泛型。因此,您可以尝试通过实现接口来实现这一点,或者实现getStudentStructs()getEmployeeStructs() 等。

标签: arrays go struct


【解决方案1】:

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

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

或者,重构您的架构或仅重构它的 Go 表示,使其不那么分层(也许人类可以扮演许多角色?),这样它就不会与 Go 的类型系统发生冲突。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2017-04-23
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多