Look at this simple example above.
- The first error is easy to understand: integers cannot be multiplied with
- The second example fixes the problem, as expected
- The third example raises the question, why is
1000 * time.Millisecondnot a problem? Is
1000also an integer?
Don’t panic, take a closer look at the difference between
rand.Intn(10) * 1000 and
1000: the former is a variable, the type has already been determined, it is reasonable to fail to compile; while the latter is a constant, the type is not
int, belongs to
untyped constants, the compiler will try to convert it to
This aroused my curiosity, what if I write a
Sure enough, it doesn’t work. So what exactly are the rules for type conversion of untyped constants?
First of all, each type of constant corresponds to a default type.
Then, take a look at the definition of
That means the default type of
int and the compiler will try to do a type conversion
int are fully compatible, so the compilation passes.