Search code examples
goassertiontypechecking

How does .(type) work in go


func test(value interface{}) {
    if res, ok := value.(string); ok {
        fmt.Println(res)
    }
}

how can go confirm the type of value? I did't find anything in struct can represent type. Please help.


Solution

  • Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

    for example:

    s:="123"
    test(s)
    

    you can think of value as (string, "123"). so when you do res, ok:=value.(string), it can find out res and ok.