V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Seanfuck

请教下 interface{} 的问题

  •  
  •   Seanfuck · Feb 13, 2023 · 1498 views
    This topic created in 1170 days ago, the information mentioned may be changed or developed.
    jstr := `{"01":[{"year":1662,"title":"ggg"},{"year":1835,"title":"uuuu"}]}`
    
    var data map[string]interface{}
    //data := map[string]interface{}{}
    //上面两种定义都可以,第二种要怎么理解,为什么要加{}?
    
    _ = json.Unmarshal([]byte(jstr), &data)
    
    //title := data["01"].([]map[string]interface{})[0]["title"] //不行
    title := data["01"].([]interface{})[0].(map[string]interface{})["title"]
    //为什么上面的方式不行,下面的行?
    
    fmt.Println(title.(string))
    
    7 replies    2023-02-14 09:45:26 +08:00
    GogoGo666
        1
    GogoGo666  
       Feb 13, 2023
    你的代码中使用 var 关键字声明的 data 没有初始化,:=声明的变量是已经初始化的,{}表示没有任何键值对

    第二个问题因为你的 json 结构决定的,01 这个 key ,对应的 value 的最顶层是个[]
    DefoliationM
        2
    DefoliationM  
       Feb 13, 2023
    上面只有类型,下面有初始化
    ****************************
    {} -> 键值对,[] -> 数组
    xuyang2
        3
    xuyang2  
       Feb 13, 2023
    因为 Go 不是 Java

    []interface{} 不是 []map[string]interface{}

    panic 报错信息已经说的很清楚了
    Seanfuck
        4
    Seanfuck  
    OP
       Feb 13, 2023
    @xuyang2 我的疑问是为什么 []interface{} 和 map[string]interface{} 可以,[]map[string]interface{} 却不行,
    我现在理解为前两者是“类型”,后者是“类型数组”所以不行,这样对不?
    Seanfuck
        5
    Seanfuck  
    OP
       Feb 13, 2023
    我又试了自定义类型
    ```
    type Evt struct {
    Year int `json:"year"`
    Title string `json:"title"`
    }
    ```
    编译无错但运行报错:
    ```
    jstr := `[{"01":[{"year":1662,"title":"ggg"},{"year":1835,"title":"uuuu"}]}]`
    var data3 []map[string]interface{}
    _ = json.Unmarshal([]byte(jstr), &data3)

    title3 := data3[0]["01"].([]interface{})[0].(Evt).Title
    fmt.Println(title3)
    ```
    这又是怎么回事,是否不能用结构体类型?求教。
    yaott2020
        6
    yaott2020  
       Feb 14, 2023 via Android
    你不用先断言吗
    kumoocat
        7
    kumoocat  
       Feb 14, 2023
    @Seanfuck
    var s any = []any{1}
    fmt.Println(s.([]int))

    s 指向的是 []any ,不能强制转换为 []int

    var m any
    _ = json.Unmarshal([]byte(`{"k":"v"}`), &m)
    fmt.Println(m)

    m 是 map ,不能强制转换为结构体
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5955 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 116ms · UTC 02:13 · PVG 10:13 · LAX 19:13 · JFK 22:13
    ♥ Do have faith in what you're doing.