Egor Kozelskij
Egor Kozelskij

Reputation: 11

Go auto type conversion - comparing inteface{} to concrete type

If I want to compare two types - string and interface{} I usually write:

package main

import "log"

func main() {
    var p1 interface{}
    var p2 string

    p1 = "123"
    p2 = "123"

    if v, ok := p1.(string); ok {
        log.Println(v == p2)
    } else {
        log.Println("false")    
    }
}

I think it is save variant when type(p1) != string. But is it correct if I write?:

package main

import "log"

func main() {
    var p1 interface{}
    var p2 string

    p1 = "123"
    p2 = "123"

    log.Println(p1 == p2)
}

If type(p1) != string there was not a error. But it is the same variant or I should write previous one?

Upvotes: 1

Views: 597

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273366

The short answer to your immediate question is yes, though the original code (first snippet in your question) shows more thoughtfulness about type checking so it could be more correct from a SW engineering point of view. It's hard to tell without understanding more context.


According to the Go spec:

Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

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.

I believe what you're asking falls under the terms of the second paragraph here.

Upvotes: 2

Related Questions