如何将类型作为参数传递

Ker*_*tis 3 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.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
  fmt.Println("error:", err)
}
fmt.Println(configuration.Users)
Run Code Online (Sandbox Code Playgroud)

如您所见,我有两种不同类型的 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
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 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)
 }
}
Run Code Online (Sandbox Code Playgroud)

像这样调用它:

var configuration Configuration
decode(&configuration)

var another AnotherConfiguration
decode(&another)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我重命名makedecode以避免隐藏内置函数