Number "implicit cast"

Please check theese simple functions:

func get_100_0() float32 {
    return float32(int(1)/100.0)
}

func get_100_1() float32 {
    return float32(int(1)/100.1)
}

Why do I get following error on one function only:
“constant 100.1 truncated to integer”,
i.e. why is 100.0 treated as integer?

https://play.golang.org/p/psJdTsWgfSK

100.0 is not treated as integer, but converted as well, but there is no difference in value between 100 and 100.0, thats why you do not get a warning there. Its a “lossless” conversion.

I am confused, now as why does Golang automatically converts a literal 100.0 to integer. It is a literal written by a coder, if a coder wanted an integer it would simply write 100, wouldnt it?
Is there some logic behind this?

From the spec:

Except for shift operations, if one operand is an untyped constant and the other operand is not, the constant is converted to the type of the other operand.

That explains “constant 100.1 truncated to integer”, for sure, but it does not explain why a literal “100.0” is considered to be a literal “100” (without quotes).

On the same page one can find explanation of floating-point literals, where “0.” is shown as an example of floating-point literal. (Note: I have tested the code with “100.” and it acts just like with “100.0”)

100.0 is not considered literal 100, but considered losslessly coercable. And even though it is a floating point literal, it’s still untyped.

Your left hand operator decided the type of the expression.

I recommend you to learn more about the untyped constants from these resources:

While the material you provide probably is of high quality, you should not take every question as an opportunity to advertise your paid content. Most of us code for a living but we don’t use this forum to promote our services. Please don’t.

4 Likes

My blog is not paid content. It’s completely free. + And I’m not linking to my blog for every answer, your comment is unfair. I think you should not police every answer with a link as an opportunity to warn people.

If I can give links about Go Blog etc, I should be able to give links to my blog when it’s relevant. If you’ve a blog and relevant content, I believe you may also give link to your own blog. There’s nothing wrong with that as long as it helps people.

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