Nagri
Nagri

Reputation: 3136

Why is a float64 type number throwing int related error in Go

I am trying to grasp Golang, in one of the tutorial example it says that An untyped constant takes the type needed by its context.

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))

    // Here Big is too large of a number but can be handled as a float64.
    // No compilation error is thrown here.
    fmt.Println(needFloat(Big))

    // The below line throws the following compilation error
    // constant 1267650600228229401496703205376 overflows int
    fmt.Println(Big)
}

When calling fmt.Println(Big) why is Golang treating Big as an int where as by context it should be float64?

What am I missing?

Upvotes: 0

Views: 1211

Answers (3)

Priyansh jain
Priyansh jain

Reputation: 1422

Simply cast the int in the float64.

floatNumber = float64(integerNumber)

Upvotes: 0

Alongkorn
Alongkorn

Reputation: 4197

Big in fmt.Println(Big) has type integer which is more than max int value 9223372036854775807

you can find max int from this logic

const MaxUint = ^uint(0)
const MaxInt = int(MaxUint >> 1)
fmt.Println(MaxInt) // print 922337

2036854775807

To fix it, you need to cast it to float64 like this

fmt.Println(float64(Big))

Upvotes: 0

Nathan Surfus
Nathan Surfus

Reputation: 129

What is the context for fmt.Println? In other words, what does fmt.Println expect Big to be? An interface{}.

From the Go Blog on Constants:

What happens when fmt.Printf is called with an untyped constant is that an interface value is created to pass as an argument, and the concrete type stored for that argument is the default type of the constant.

So the default type of the constant must be an int. The page goes on to talk about how the defaults get determined based on syntax, not necessarily the value of the const.

Upvotes: 4

Related Questions