V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Seanfuck
V2EX  ›  Go 编程语言

请教下 interface{} 的问题

  •  
  •   Seanfuck · 2023-02-13 15:37:35 +08:00 · 861 次点击
    这是一个创建于 435 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2023-02-14 09:45:26 +08:00
    GogoGo666
        1
    GogoGo666  
       2023-02-13 15:54:30 +08:00
    你的代码中使用 var 关键字声明的 data 没有初始化,:=声明的变量是已经初始化的,{}表示没有任何键值对

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

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

    panic 报错信息已经说的很清楚了
    Seanfuck
        4
    Seanfuck  
    OP
       2023-02-13 22:23:25 +08:00
    @xuyang2 我的疑问是为什么 []interface{} 和 map[string]interface{} 可以,[]map[string]interface{} 却不行,
    我现在理解为前两者是“类型”,后者是“类型数组”所以不行,这样对不?
    Seanfuck
        5
    Seanfuck  
    OP
       2023-02-13 22:34:44 +08:00
    我又试了自定义类型
    ```
    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  
       2023-02-14 09:41:22 +08:00 via Android
    你不用先断言吗
    kumoocat
        7
    kumoocat  
       2023-02-14 09:45:26 +08:00
    @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 ,不能强制转换为结构体
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3334 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:31 · PVG 20:31 · LAX 05:31 · JFK 08:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.