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 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题