Hephaestus
Hephaestus

Reputation: 2072

Direct comparison of Go interface{} to built-in types: Why does this work?

Why does the following Go code work?

That is, since the types of f and b are interface{} (and not any of bool, int or string), how is it possible for me to get away with not casting or type-asserting f and b in each of the three if statements?

package main

import (
    "fmt"
    "reflect"
)

func foop(p map[string]interface{}) {
    p["foo"] = true
}

func barp(p map[string]interface{}) {
    p["bar"] = 17
}

func foop2(p map[string]interface{}) {
    p["foo"] = "blah"
}

func main() {
    p := make(map[string]interface{})
    fmt.Printf("%v\n", p)

    foop(p)
    barp(p)
    f := p["foo"]
    b := p["bar"]
    fmt.Printf("f: %T\n", f)
    if f == true {
        fmt.Println("ok")
    }
    fmt.Printf("b: %T\n", b)
    if b == 17 {
        fmt.Println("ok")
    }

    foop2(p)
    f = p["foo"]
    if f == "blah" {
        fmt.Println("ok")
    }
    fmt.Printf("f: %T\n", f)
    fmt.Printf("f: %s\n", reflect.TypeOf(f))
}

(Go Playground: https://play.golang.org/p/kPi25yW6tF)

Upvotes: 3

Views: 164

Answers (1)

JimB
JimB

Reputation: 109331

As with most Go language questions, the answer is in the Go Programming Language Specification, specifically the section on Comparison Operators.

A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x.

Upvotes: 5

Related Questions