No panic when converting int to uint?

Issue

I’m confused about the following type conversion. I would expect both uint conversions to panic.

a := -1
_ = uint(a) // why no panic?

_ = uint(-1) // panics: constant -1 overflows uint

Why doesn’t it panic in line 2?

https://play.golang.org/p/jcfDL8km2C

Solution

As mentioned in issue 6923:

T(c) where T is a type and c is a constant means to treat c as having type T rather than one of the default types.
It gives an error if c can not be represented in T, except that for float and complex constants we quietly round to T as long as the value is not too large.

Here:

const x uint = -1
var x uint = -1

This doesn’t work because -1 cannot be (implicitly) converted to a uint.

_ = uint(a) // why no panic?

Because a is not an untyped constant, but a typed variable (int). See Playground and "what’s wrong with Golang constant overflows uint64":

package main

import "fmt"

func main() {
    a := -1
    _ = uint(a) // why no panic?
    var b uint
    b = uint(a)
    fmt.Println(b)
    // _ = uint(-1) // panics: main.go:7: constant -1 overflows uint
}

Result: 4294967295 (on 32-bits system) or 18446744073709551615 (on 64-bits system), as commented by starriet

That are specific rules for the conversion of non-constant numeric values:

When converting between integer types, if the value is a signed integer, it is sign extended to implicit infinite precision; otherwise it is zero extended.
It is then truncated to fit in the result type’s size.

Answered By – VonC

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.