2016-11-10 6 views
0

どうやら、DRYを維持するために関数パラメータ(getOc​​cupationStructs関数)に基づいて構造体の配列を返したいと思いますが、それは不可能なようです。エラー:Go関数で構造体の動的配列を返すことはできますか?

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

この問題を対処するために、有効な回避策はありますか?

+0

エラーは何ですか? – Nadh

+0

@Nadh私はすでに質問に追加しました。私に思い出させることに感謝します – mlxjr

+0

答えには何も指摘されていないので、Goには構造的なサブタイプがありません。ジェネリックもありません。したがって、インターフェースを実装するか、 'getStudentStructs()'、 'getEmployeeStructs()'などを実装することで、これを実現することができます。 – Nadh

答えて

1

Goには構造的なサブタイプがありません。したがって、多型を得るにはインタフェースを使用する必要があります。

すべての構造体型が実装するインターフェイスを定義します。interface embedsHuman { Name() string }のようにプライベートにすることもでき、[]embedsHumanを返します。

また、Goのタイプのシステムと衝突しないように、スキーマやGoの表現だけを階層的ではないもの(多分人間は多くの役割を持つことができます)として再構成します。

関連する問題