2015-09-01 40 views
5

我在寫一個解析配置JSON文件並使用json.Unmarshal將其數據存儲在結構中的函數。我已經做了一些研究,它讓我知道了配置結構和Server_Config結構作爲config中的一個字段,以允許我添加更多的字段,因爲我需要不同的類似配置的結構。如何編寫一個Go函數來接受不同的結構體?

如何編寫一個parseJSON函數以適用於不同類型的結構?

代碼:

Server.go

type Server_Config struct { 
    html_templates string 
} 

type Config struct { 
    Server_Config 
} 

func main() { 
    config := Config{} 
    ParseJSON("server_config.json", &config) 
    fmt.Printf("%T\n", config.html_templates) 
    fmt.Printf(config.html_templates) 
} 

config.go

package main 
import(
    "encoding/json" 
    "io/ioutil" 
    "log" 
) 

func ParseJSON(file string, config Config) { 
    configFile, err := ioutil.ReadFile(file) 
    if err != nil { 
     log.Fatal(err) 
    } 
    err = json.Unmarshal(configFile, &config) 
    if err != nil { 
     log.Fatal(err) 
    } 
} 

或者,如果有更好的方式來做到這一切讓我知道,作爲好。 Go非常新,我將Java約定刻在我的大腦中。

回答

6

使用interface{}

func ParseJSON(file string, val interface{}) { 
    configFile, err := ioutil.ReadFile(file) 
    if err != nil { 
     log.Fatal(err) 
    } 
    err = json.Unmarshal(configFile, val) 
    if err != nil { 
     log.Fatal(err) 
    } 
} 

調用函數是一樣的。

+0

哦,太棒了。那麼爲什麼/如何工作? – mbridges

+1

'interface {}'是最接近你在Go中得到的泛型類型,你可以使用它來傳遞任何類型,json然後使用['reflect'](http://golang.org/pkg/reflect/) )來處理它。 – OneOfOne

相關問題