2

I've found that you can cast a variable int32 to uint32 but you cannot cast a const int32 to uint32.

See here: https://play.golang.org/p/tDm6B6g5P6u

If line 14 is commented out it works.

Does anyone have an explanation for this?

Thanks!

Flimzy
  • 68,325
  • 15
  • 126
  • 165
jcmturner
  • 113
  • 1
  • 3
  • Just to add the behaviour is the same with int64 to uint64 and int to uint – jcmturner Jan 26 '18 at 20:50
  • The most technically correct reason is because Go doesn't support type casting at all. The real question you mean to ask is probably "Why can't I convert an int32 to a uint32?" – Flimzy Jan 27 '18 at 11:03

1 Answers1

3

The expression uint32(ci) is a constant expression. The spec says this about constant expressions:

The values of typed constants must always be accurately representable as values of the constant type.

A uint32 cannot accurately represent the negative value ci, therefore this expression results in a compilation error.

Positive values in range are supported. For example, uint32(-ci) compiles with no error.

The expressions uint32(vi) and uint32(vc) are conversions. Conversions betweeen numeric types are allowed, even when there's loss of accuracy.

Bayta Darell
  • 101,448
  • 10
  • 207
  • 215
  • However just to add you can cast it if your value is a positive number, see https://play.golang.org/p/ZlUYXCWYx0r - as long as it can be represented accurately that's fine. – Ravi R Jan 27 '18 at 03:17