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

前端 未结 7 1261
青春惊慌失措
青春惊慌失措 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:30

    You also can do type switches:

    switch v := myInterface.(type) {
    case int:
        // v is an int here, so e.g. v + 1 is possible.
        fmt.Printf("Integer: %v", v)
    case float64:
        // v is a float64 here, so e.g. v + 1.0 is possible.
        fmt.Printf("Float64: %v", v)
    case string:
        // v is a string here, so e.g. v + " Yeah!" is possible.
        fmt.Printf("String: %v", v)
    default:
        // And here I'm feeling dumb. ;)
        fmt.Printf("I don't know, ask stackoverflow.")
    }
    

提交回复
热议问题