Conversions in Go
Go converts explicitly: no implicit promotion, ever.
type Celsius float64
func conversions(text string) (int, string, Celsius, error) {
big := 300
asByte := byte(big % 256) // explicit, and it wraps
parsed, err := strconv.Atoi(text)
if err != nil {
return 0, "", 0, fmt.Errorf("parse %q: %w", text, err)
}
formatted := strconv.FormatFloat(1.5, 'f', 2, 64)
temperature := Celsius(float64(parsed))
return int(asByte) + parsed, formatted, temperature, nil
}
How it works
- A numeric conversion can silently truncate, so bound it first.
strconvconverts between strings and numbers, with an error.- A named type needs a conversion even when the underlying type matches.
Keywords and builtins used here
byteerrorfloat64funcifintreturnstringtype
The run, in numbers
- Lines
- 16
- Characters to type
- 405
- Tokens
- 101
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 76 seconds.
Step 4 of 5 in Variables & types, step 4 of 30 in Language basics.