How does the constant value auto type work in golang?

Viewed 436

Here is the code snippet:

a := 40
f := float64(a/100.0)
fmt.Println("Hello, playground", f)

f=0, why?

2 Answers

Spec: 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, for instance, in a short variable declaration such as i := 0 where there is no explicit type. 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.

a := 40 is a short variable declaration, the untyped integer constant 40 has a default type int, so a will be of type int.

In a/100.0 since a is of type int and 100.0 is representable by an integer, it will take the type of int, and a/100.0 will be an integer division, resulting in 0.

This 0 int value will be then converted to float64.

Note that if you would change the first line to:

a := 40.0

Then the output would be 0.4 because the 40.0 is an untyped floating point literal and so it has a default type of float64. So a will be of type float64, and a/100.0 will be a floating-point division, resulting in 0.4. Try it on the Go Playground.

You would get the same result if you'd use a typed constant, because here no default type is used, float64(40) is a typed constant, obviously of type float64 (try it on the Go Playground):

a := float64(40)

See The Go Blog: Constants.

Here default type for a is int since you use a:=40 and but 100.0 is just a constant so no auto-detect of type for variable. So a/100.0 consider as integer division and which result is 0 which means f := float64(0) executed

Case Analysis

If you set 100.0 in a variable.

a := 40
b := 100.0
f := float64(a/b)

Then b is a float64 type. So you get error like

invalid operation: a / b (mismatched types int and float64)

Because you are trying to do divide operation with two different type

And if type cast a into float64() then it works

a := 40
b := 100.0
f := float64(a)/b

So, here both variable is float64 type in divide operation.

Now, as we cast a into float64 then in divide operation we can directly use 100.0 without variable.

a := 40
f := float64(a)/100.0
Related