dsh1956 2014-10-14 15:12
浏览 43
已采纳

接口指针作为函数参数

This most likely stems from a misunderstanding of what interface{} is in go. I have the following code

type Configuration struct {
    Username string
}

func loadJson(jsonStr []byte, x *Configuration}) {
    json.Unmarshal(jsonStr, x)
}

func main() {
    //var config *Configuration
    config := new(Configuration)
    file, e := ioutil.ReadFile("config.json")
    loadJson(file, config)
    fmt.Printf("%s
", config.Username)
}

It loads a json configuration into the config variable. I want to make the loadJson function more abstract and accept any struct. I thought the best way to do that would be to accept a *interface{}, however I get the following error when changing the loadJson Signature.

 ./issue.go:30: cannot use config (type *Configuration) as type *interface {} in argument to loadJson:
*interface {} is pointer to interface, not interface

Instead load json should be this

func loadJson(jsonStr []byte, x interface{}}) {
    json.Unmarshal(jsonStr, x)
}

Is interface{} already a pointer? Also the error message doesn't make the most sense to me, isn't configuration a pointer to an interface? Also, if I change json.Unmarshal(jsonStr, x) to json.Unmarshal(jsonStr, &x) it will work perfectly fine still. What is going on here that allows that to work?

Side question but relevant to pointers, why can't I declare a pointer like the commented out line(under main)?

展开全部

  • 写回答

3条回答 默认 最新

  • dongyong3554 2014-10-14 16:26
    关注

    Use interface{} to represent any type including pointers:

    func loadJson(jsonStr []byte, x interface{}) {
       json.Unmarshal(jsonStr, x)
    }
    

    <kbd>playground</kbd>

    Although you can assign a Configuration to an interface{}, the memory layout of a Configuration value and an interface{} value are different. Because the memory layouts are different, a pointer to an interface{} cannot be converted to a pointer to a Configuration. The same reasoning applies to a []T and a []interface[}.

    It's rare to user a pointer to an interface in Go.

    Regarding the side note: You can use a variable declaration and assignment

    var config *Configuration
    config = new(Configuration)
    

    or you can use a short variable declaration:

    config := new(Configuration)
    

    You cannot use declaration and short declaration together because it declares the variable twice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了