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

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

    Your example does work. Here's a simplified version.

    package main
    
    import "fmt"
    
    func weird(i int) interface{} {
        if i < 0 {
            return "negative"
        }
        return i
    }
    
    func main() {
        var i = 42
        if w, ok := weird(7).(int); ok {
            i += w
        }
        if w, ok := weird(-100).(int); ok {
            i += w
        }
        fmt.Println("i =", i)
    }
    
    Output:
    i = 49
    

    It uses Type assertions.

    0 讨论(0)
提交回复
热议问题