Why type conversion overflows?

If I compile the code below:

package main

import (
	"fmt"
	"math"
)

func main() {
	b := uint32(-1)
	fmt.Printf("%d, %v, %b\n", b, b == math.MaxUint32, math.MaxUint32)
}

I got an error:

constant -1 overflows uint32

But if I change the code:

package main

import (
	"fmt"
	"math"
)

func main() {
	a := -1
	b := uint32(a)
	fmt.Printf("%d, %v, %b\n", b, b == math.MaxUint32, math.MaxUint32)
}

It works. Iโ€™m wondering the reason, can somebody explain? thx :slight_smile:

In Go, constants donโ€™t have types. In constant expressions, -1 really is just the conceptual value, -1. The set of allowed values for a uint32 is [0, 2^32) and -1 is not in that set. It looks like you wanted a uint32 with all bits set to 1s. Two easy ways to do that in Go are:

const (
 b0 = uint32(math.MaxUint32)  // pre-defined constant
 b1 = ^uint32(0)              // invert the bits of a uint32 0
)
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.