Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printing out max int cause compile error in golang?

Tags:

go

Here is a link to go playground

package main

import "fmt"
import "math"
func main() {
    fmt.Println("Hello, playground")
    fmt.Println(math.MaxUint32)
}

The above code seems to cause

constant 4294967295 overflows int

does fmt.Println convert every number to int automatically?

like image 204
Kevin Avatar asked Mar 26 '16 02:03

Kevin


People also ask

What is Max INT in Golang?

The MaxInt constant is an inbuilt constant of the math package which is used to get the highest (maximum) value that can be represented by an int.

Does Golang need a runtime?

Does Go have a runtime? Go does have an extensive library, called the runtime, that is part of every Go program. The runtime library implements garbage collection, concurrency, stack management, and other critical features of the Go language.


1 Answers

The Go Programming Language Specification

Constants

An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required. The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.

func Println(a ...interface{}) (n int, err error)

fmt.Println(math.MaxUint32)

math.MaxUint32 is an untyped integer constant that defaults to type int in this context, an untyped integer constant argument for a type interface{} parameter.

int is a signed 32- or 64-bit integer depending on the implementation.

const (
    MaxInt32  = 1<<31 - 1
    MaxUint32 = 1<<32 - 1
)

MaxUint32 is greater than MaxInt32.

if you run go env you should see that you are using a 32-bit architecture, for example, GOARCH="386".

Don't accept the default 32-bit int type. Use a compatible type conversion. For example, write

fmt.Println(uint32(math.MaxUint32))
like image 154
peterSO Avatar answered Oct 10 '22 13:10

peterSO