如何将类型作为参数传递

3

我有一段解析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
}
1个回答

5
编写解码函数以接受指向要解码的值的指针:
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)
 }
}

这样调用:

var configuration Configuration
decode(&configuration)

var another AnotherConfiguration
decode(&another)

顺便说一下,我将make重命名为decode,以避免与内置函数重名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接