我有一段解析json配置文件的代码:
import (
"encoding/json"
"os"
"fmt"
)
type Configuration struct {
Users []string
Groups []string
}
type AnotherConfiguration struct {
Names []string
}
file, _ := os.Open("conf.json")
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(configuration.Users)
正如您所看到的,我有两种不同类型的配置(Configuration和AnotherConfiguration)。
我无法想出如何创建一个通用函数,它可以返回任何类型的配置(Configuration或AnotherConfiguration)。
类似于这样:
func make(typename) {
file, _ := os.Open("conf.json")
decoder := json.NewDecoder(file)
configuration := typename{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
return configuration
}