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

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

Pointer to slice of interfaces in function parameter

问题

我有以下函数:

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

我像这样调用它:

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

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

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

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

英文:

I have the following function:

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

Which I call like this:

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

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

  1. ./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

声明函数如下:

  1. func read(filePath string, structure interface{}) error {
  2. raw, err := ioutil.ReadFile(filePath)
  3. if err != nil {
  4. return err
  5. }
  6. return json.Unmarshal(raw, structure)
  7. }

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

调用方式如下:

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

Declare the function like this:

  1. func read(filePath string, structure interface{}) error {
  2. raw, err := ioutil.ReadFile(filePath)
  3. if err != nil {
  4. return err
  5. }
  6. return json.Unmarshal(raw, structure)
  7. }

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

Call it like this:

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

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:

确定