How does golang judge whether two variables are equal when the value of two variables is unknown?

recently, learning go wants to judge whether two variables are equal or not. It is found that if the two variables are assigned different types, they will directly report an error when using if judgment

.
.\test.go:123:8: invalid operation: c == d (mismatched types int and float64)

here is my code to ask the bosses how to judge if this is the case

package main 
import (
    "fmt"
    "reflect"
)
func main() {

    c := 1
    d := 1.1
    ct := reflect.TypeOf(c)
    dt := reflect.TypeOf(d)
    fmt.Println("!!!!!!!!!!!!!!!!!!")
    fmt.Println(ct)
    fmt.Println(dt)

    if ct == dt {
        fmt.Println("")
        if c == d {
            fmt.Println("")
        } else {
            fmt.Println("")
        }
    } else {
        fmt.Println("")
    }
}
Apr.17,2022

according to the intention of the main code of the question, you can directly use the reflect.DeepEqual function to compare, that is,

package main

import (
    "fmt"
    "reflect"
)

func main() {
    c := 1
    d := 1.1
    fmt.Println(reflect.DeepEqual(c, d))
}

cannot be compared. It cannot be passed when compiling.


impassable types cannot determine whether they are equal or not. You need to convert the values of both types to the same type.


Type conversion


  1. first type assertion to check whether the type is the same
  2. if the type is the same, check the value
Menu