dqybjj3497 2016-11-10 05:36
浏览 323
已采纳

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

Apparently, I want to return an array of struct based on the function parameter (getOccupationStructs function) in order to keep DRY (not using if else in every other functions), but it seems impossible to do, so here is my errors:

 cannot use []Student literal (type []Student) as type []struct {} in
   return argument
 cannot use []Employee literal (type []Employee ) as type []struct {} in
   return argument

and here is my code:

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)
    }
}

Is there any valid workaround to cope this problem?

  • 写回答

1条回答 默认 最新

  • douying8666 2016-11-10 05:46
    关注

    Go doesn't have structural subtyping, so to get polymorphism you'll need to use an interface.

    Define an interface that all struct types implement, it can even be private, like interface embedsHuman { Name() string }, and then return []embedsHuman.

    Alternatively, restructure your schema or only the Go representation of it as something less hierarchical (perhaps humans can have many roles?), so that it doesn't clash with Go's type system.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?