How to determine an interface{} value's “real” type?

前端 未结 7 1282
青春惊慌失措
青春惊慌失措 2020-12-22 17:15

I have not found a good resource for using interface{} types. For example

package main

import \"fmt\"

func weirdFunc(i int) interface{} {
             


        
7条回答
  •  难免孤独
    2020-12-22 17:29

    Here is an example of decoding a generic map using both switch and reflection, so if you don't match the type, use reflection to figure it out and then add the type in next time.

    var data map[string]interface {}
    
    ...
    
    for k, v := range data {
        fmt.Printf("pair:%s\t%s\n", k, v)   
    
        switch t := v.(type) {
        case int:
            fmt.Printf("Integer: %v\n", t)
        case float64:
            fmt.Printf("Float64: %v\n", t)
        case string:
            fmt.Printf("String: %v\n", t)
        case bool:
            fmt.Printf("Bool: %v\n", t)
        case []interface {}:
            for i,n := range t {
                fmt.Printf("Item: %v= %v\n", i, n)
            }
        default:
            var r = reflect.TypeOf(t)
            fmt.Printf("Other:%v\n", r)             
        }
    }
    

提交回复
热议问题