-1

In A Tour of Go, section Numeric Constants, the code is

package main

import "fmt"

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other words, the binary number that is 1 followed by 100 zeroes.
    Big = 1 << 100
    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }

func needFloat(x float64) float64 { return x * 0.1 }

func main() {
    fmt.Println(needInt(Small))
    fmt.Println(needFloat(Small))
    fmt.Println(needFloat(Big))

    fmt.Println(Big * 0.1) //one
    fmt.Println(Big / 10)  //two
}

fmt.Println(Big*0.1) output 1.2676506002282295e+29, but fmt.Println(Big / 10) throw an error:constant 126765060022822940149670320537 overflows int, what's difference between them.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
joystrong
  • 11
  • 2
  • Please read https://blog.golang.org/constants . Summing up: Constant can be arbitrary precision/large. But sometimes a constant must be converted to a real Go type. In your case a float and an int. Not every constant can be converted an this is a compile time error. The difference is: `Big*0.1` is converted to float while `Big/10` is converted to int. Details in the blog post. – Volker Oct 31 '19 at 04:37

1 Answers1

0

From the Go blog on constants:

Numeric constants live in an arbitrary-precision numeric space; they are just regular numbers. But when they are assigned to a variable the value must be able to fit in the destination.

An example may make this clearer:

const f = 1 << 31

x := f / 10  // what type is x?
y := f * 0.1 // what type is y?

fmt.Printf(" 10 : type = %8T\n", 10)    // int
fmt.Printf("0.1 : type = %8T\n\n", 0.1) // float64

fmt.Printf(" x  : type = %8T  value = %v\n", x, x)
fmt.Printf(" y  : type = %8T  value = %v\n", y, y)

Playground output:

 10 : type =      int
0.1 : type =  float64

 x  : type =      int  value = 214748364
 y  : type =  float64  value = 2.147483648e+08

  • x is an int since the devisor 10 is interpreted as an int.
  • y is a float64 since the multiplier 0.1 is interpreted as a float64.

In the tour example, the const is 1<<100, which is too large to fit into an int (32-bits), so the program will fail to even compile, as the number cannot be stored into the allocated memory type: 100 bits will not fit into a 32-bit int.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52