dsh1956 2014-10-14 23: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-15 00: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 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集