Go core · 3 MIN READ
Go never converts a number for you
Fix a mismatched-type expression without guessing.
There is no implicit numeric conversion in Go. An int and an int64 are different types even where they are the same width, and adding them is an error rather than a promotion. The fix is always an explicit conversion, and the point of the rule is that the place where precision could be lost is visible in the source.
A named type behaves the same way. type Celsius float64 cannot be added to a float64 without saying so, which is exactly what makes named types worth declaring: the compiler stops you mixing units.
SEE THE IDEA
Make the type change visible
- 01
Distinct types
gotype Meters float64A named type protects a meaning
- 02
Explicit conversion
gofloat64(distance)Choose a common numeric type
- 03
Operation
gosum / float64(count)Both operands now agree
Equal storage widths do not make two numeric types interchangeable.
In practice
Choose the result type before choosing a conversion. Converting an integer to a float can lose precision for large values; converting a float to an integer truncates the fractional part. An explicit conversion documents the decision, but it does not make a lossy conversion harmless.
Watch out
Check an empty collection before dividing by its length. Type correctness alone does not prevent division by zero.
Work through the exercise
package main
type Celsius float64
// Average returns the mean of the readings, in Celsius.
// count is an int and the sum is a Celsius; make them agree.
func Average(readings []Celsius) Celsius {
var sum Celsius
for _, r := range readings {
sum += r
}
return sum / len(readings)
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.