Type Judgment of Empty interface

Empty interfaces can store any type of data, and when you need to determine what type it is, you can use the following methods.

1 Direct assertion

For example, we receive a variable unknown of type interface {}, which can be directly asserted as a string type by the following code:

val, ok := unknow.(string)

If the return ok is true, the variable unknowown is of string type, and a val ue storing string type is returned.
If we decide that unknown is a string type, we can also forcibly retrieve its value without returning the ok variable:

val := unknow.(string)

However, there is a certain risk in using this method. If it is not a string type, panic will occur:

panic: interface conversion: interface {} is int, not string

2 reflection

Reflections are located in the relfect package. The retrieved type uses reflect.TypeOf, and the retrieved value uses reflect.ValueOf.

retType = reflect.TypeOf(unknow)
val = reflect.ValueOf(unknow)

3-type keyword judgment

This method must be applicable to switch case, and different cases can be used for different processing.

switch unknow.(type){
    case string:
        //string type
    case int:
        //int type
}

Illustrate with examples

This example uses the various methods listed above to determine the type and value of a string.

package main

import (
    "fmt"
    "reflect"
)

func main(){
    var str interface{} = "abc"

    retType,val := interfaceAssert1(str)
    fmt.Printf("type:%v, value:%v\n", retType, val)

    retType2,val2 := interfaceAssert2(str)
    fmt.Printf("type:%v, value:%v\n", retType2, val2)

    retType3 := interfaceAssert3(str)
    fmt.Printf("type:%v\n", retType3)

}

//Direct assertion
func interfaceAssert1(unknow interface{})(retType string, val interface{}){
    val, ok := unknow.(string)

    if ok{
        return "string", val
    }else{
        return "not string", nil
    }

}

//reflex
func interfaceAssert2(unknow interface{})(retType reflect.Type, val reflect.Value){
    retType = reflect.TypeOf(unknow)
    val = reflect.ValueOf(unknow)
    return retType,val
}

//type keyword
func interfaceAssert3(unknow interface{})(retType string){
    switch unknow.(type){
    case string:
        return "string"
    case int:
        return "int"
    default:
        return "other type"
    }
}

Tags: Go

Posted on Sat, 12 Oct 2019 10:17:55 -0700 by oscar2