简体   繁体   English

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

[英]Q: golang pointer to map[string]interface{}

I (golang newbie) am trying to create a map[string]interfaces{} in a function. 我(golang新手)正在尝试在函数中创建map [string] interfaces {}。 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. 我发现本文描述了如何使用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\n",  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. 因此,我认为我的问题与映射的类型为接口而不是字符串有关,但我无法确定为什么第一个代码不起作用而第二个代码却不起作用。

There's a number of things causing confusion here: 造成混乱的原因有很多:

  • You don't need b at all. 您根本不需要b 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. 我们不需要指向sJson字符串的指针。 Strings are immutable, and you're not trying to reassign the sJson variable. 字符串是不可变的,并且您没有尝试重新分配sJson变量。
  • You're unmarshaling into an empty interface, and then trying to reassign the myMap variable to the contents of f . 您正在将编组到一个空接口中,然后尝试将myMap变量重新分配给f的内容。 Since myMap isn't a pointer, that assignment is only scoped to within the function. 由于myMap不是指针,因此该赋值仅作用于函数内。 Just unmarshal directly into myMap 只需直接将myMap解组到myMap

If you change those things, you'll find the json2map function ends up being one line, and can be dropped altogether: 如果更改了这些内容,您会发现json2map函数最终json2map一行,可以完全删除:

func json2map(sJson string, myMap map[string]interface{}) error {
    return json.Unmarshal([]byte(sJson), &myMap)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM