dsfovbm931034814 2015-11-24 13:55
浏览 203
已采纳

问:golang指向map [string] interface {}的指针

I (golang newbie) am trying to create a map[string]interfaces{} in a function. The code compiles and runs but the map is empty.

package main

import (
    "fmt"   
    "encoding/json" 
)


func main() {
    var f interface{}
    var sJson string                    // JSON string from VT
    var err error                       // errors
    var b []byte                        // bytearray of JSON string
    var rootMap map[string]interface{}

    rootMap = make(map[string]interface{})

    sJson=`{"key": "foo"}`

    fmt.Println(sJson)

    err = json2map(&b, &sJson, f, rootMap)

    if err != nil { return }

    switch v := rootMap["key"].(type) {
        case float64:
            fmt.Printf("Value: %d",v)
        case string:
            fmt.Printf("Value: %s", v)
        case nil:
            fmt.Println("key is nil")           
        default:
            fmt.Println("type is unknown")          
    }       
}

func json2map(b *[]byte, sJson *string, f interface{}, myMap map[string]interface{}) error {
    var err error
    *b = []byte(*sJson) 
    err = json.Unmarshal(*b,&f) 
    myMap = f.(map[string]interface{})
    return err
}

The output is:

{"key": "foo"}
key is nil

I found this article which describes how to use map[string]string. This code works as expected:

package main

import (
    "fmt"
)

type MyType struct {
    Value1 int
    Value2 string
}

func main() {
    myMap := make(map[string]string)
    myMap["key"] = "foo"
    ChangeMyMap(myMap)  
    fmt.Printf("Value : %s
",  myMap["key"])    
}

func ChangeMyMap(TheMap map[string]string) {
    TheMap["key"] = "bar"
}

So I think my problem has to do with the map being of type interface instead of string but I cannot tell why the first code doesn't work, while the 2nd does.

  • 写回答

1条回答 默认 最新

  • doukuipai8544 2015-11-24 14:04
    关注

    There's a number of things causing confusion here:

    • You don't need b at all. You're passing a pointer to a byte slice that you're reassigning inside the function. Just use the string directly.
    • There's no need to us a pointer to the sJson string. Strings are immutable, and you're not trying to reassign the sJson variable.
    • You're unmarshaling into an empty interface, and then trying to reassign the myMap variable to the contents of f. Since myMap isn't a pointer, that assignment is only scoped to within the function. Just unmarshal directly into myMap

    If you change those things, you'll find the json2map function ends up being one line, and can be dropped altogether:

    func json2map(sJson string, myMap map[string]interface{}) error {
        return json.Unmarshal([]byte(sJson), &myMap)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘