Go 如何将类型作为参数传递
我有解析json配置的代码:Go 如何将类型作为参数传递,go,Go,我有解析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.N
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)
如您所见,我有两种不同类型的配置和另一种配置
我不太明白如何创建一个泛型函数,它将返回任何类型(配置或其他配置)的配置
大概是这样的:
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
}
var configuration Configuration
decode(&configuration)
var another AnotherConfiguration
decode(&another)
编写解码函数以接受指向要解码的值的指针:
func decode(v interface{}) {
file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
err := decoder.Decode(v)
if err != nil {
fmt.Println("error:", err)
}
}
可以这样称呼:
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
}
var configuration Configuration
decode(&configuration)
var another AnotherConfiguration
decode(&another)
顺便说一句,我将make
重命名为decode
,以避免阴影阴影