函数参数中的接口切片指针

huangapple go评论88阅读模式
英文:

Pointer to slice of interfaces in function parameter

问题

我有以下函数:

func read(filePath string, structure *[]interface{}) {
    raw, err := ioutil.ReadFile(filePath)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    json.Unmarshal(raw, structure)
}

我像这样调用它:

indexes := []Index{}
read(path + "/" + element + ".json", &indexes)

然而,当我从函数声明中删除structure *[]interface{}时,我得到一个奇怪的错误:

./index.verb.go:73: syntax error: unexpected ), expecting {

我认为在尝试传递一个指向通用类型切片的指针时出了问题。那么我应该如何做呢?我不能使用structure *[]Index,因为我还想返回其他类型。

英文:

I have the following function:

func read(filePath string, structure *[]interface) {
    raw, err := ioutil.ReadFile(filePath)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    json.Unmarshal(raw, structure)
}

Which I call like this:

    indexes := []Index
    read(path + "/" + element + ".json", &indexes)

However, I'm getting strange error that vanish when I take off structure *[]interface from the function declaration:

./index.verb.go:73: syntax error: unexpected ), expecting {

I think something wront when I try to pass a pointer to a slice of generic type. How should I do it then? I can't do structure *[]Index because there are other types I wanna return too

答案1

得分: 0

声明函数如下:

func read(filePath string, structure interface{}) error {
  raw, err := ioutil.ReadFile(filePath)
  if err != nil {
    return err
  }
  return json.Unmarshal(raw, structure)
}

structure 值会传递给 json.Unmarshal,可以是任何 json.Unmarshal 支持的类型。

调用方式如下:

var indexes []Index
err := read(path + "/" + element + ".json", &indexes)
if err != nil {
    fmt.Println(err.Error())
    os.Exit(1)
}
英文:

Declare the function like this:

func read(filePath string, structure interface{}) error {
  raw, err := ioutil.ReadFile(filePath)
  if err != nil {
    return err
  }
  return json.Unmarshal(raw, structure)
}

The structure value is passed through to json.Unmarshal and can be any type supported by json.Unmarshal.

Call it like this:

var indexes []Index
err := read(path + "/" + element + ".json", &indexes)
if err != nil {
    fmt.Println(err.Error())
    os.Exit(1)
}

huangapple
  • 本文由 发表于 2017年2月16日 07:03:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/42261752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定