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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?