2016-11-07 139 views
-1

我需要一個很大的結構表,我需要去掉返回的結構。Golang return map [string] interface {}返回變量struct

package main 

import (
    "fmt" 
) 

var factory map[string]interface{} = map[string]interface{}{ 
    "Date":         Date{}, 
    "DateTime":        DateTime{}, 
} 

type Date struct { 
    year int //xsd:int Year (e.g., 2009) 
    month int //xsd:int Month (1..12) 
    day int //xsd:int Day number 
} 

func(d *Date) Init(){ 
    d.year = 2009 
    d.month = 1 
    d.day = 1 
} 

type DateTime struct { 
    date  Date //Date 
    hour  int //xsd:int 
    minute  int //xsd:int 
    second  int //xsd:int 
    timeZoneID string //xsd:string 
} 

func(d *DateTime) Init(){ 
    d.hour = 0 
    d.minute = 0 
    d.second = 0 

} 

func main() { 
    obj := factory["Date"] 
    obj.Init() 
    fmt.Println(obj) 

} 

Go Playground ,但我得到的錯誤obj.Init未定義(類型接口{}是沒有方法的接口)有沒有辦法做到這一點?

回答

2

基本上,你需要告訴編譯器你的所有類型(地圖中的實例)總是有一個Init方法。爲此,您使用Init方法聲明一個接口並構建該接口的映射。 由於您的接收器在指針* xxx上工作,因此您需要將對象的指針添加到地圖(而不是對象本身),方法是在它們前面添加&。

package main 

import (
    "fmt" 
) 

type initializer interface { 
    Init() 
} 

var factory map[string]initializer = map[string]initializer{ 
    "Date":  &Date{}, 
    "DateTime": &DateTime{}, 
} 

type Date struct { 
    year int //xsd:int Year (e.g., 2009) 
    month int //xsd:int Month (1..12) 
    day int //xsd:int Day number 
} 

func (d *Date) Init() { 
    d.year = 2009 
    d.month = 1 
    d.day = 1 
} 

type DateTime struct { 
    date  Date //Date 
    hour  int //xsd:int 
    minute  int //xsd:int 
    second  int //xsd:int 
    timeZoneID string //xsd:string 
} 

func (d *DateTime) Init() { 
    d.hour = 0 
    d.minute = 0 
    d.second = 0 

} 

func main() { 
    obj := factory["Date"] 
    obj.Init() 
    fmt.Println(obj) 

} 
相關問題