Search code examples
goconstantstypechecking

Question about operations that mix numeric types in Go


I know that Go is a statically typed language that doesn't allow operations that mix numeric types, for example, you can't add an int to a float64:

package main

import (
    "fmt"
)

func main() {
        var a int = 1
        var b float64 = 1.1
        fmt.Println(a + b)
}

Running this program will cause an error:

invalid operation: a + b (mismatched types int and float64)

But when I do the math 1 + 1.1 without declaring the variables, the program returns the desired result which is 2.1:

package main

import (
    "fmt"
)

func main() {
        fmt.Println(1 + 1.1)
}

So my question is: Why does 1 + 1.1 work? What's the numeric type of 1 and 1.1 when I use them directly in the addition?


Solution

  • As mentioned by @Volker, this is because 1 + 1.1 is evaluated as an untyped constant expression.

    So below program also works because now a and b are both untyped constant.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
            const a = 1
            const b = 1.1
            fmt.Println(a + b)
    }