Go uses explicit conversions when a value needs a different type.

type conversion A conversion such as `float64(value)` creates a value of the target type.

Type Conversion

whole
type_conversion.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var whole = 7
	half := float64(whole) / 2.0
	label := fmt.Sprintf("%.1f", half)

	fmt.Println("whole=", whole)
	fmt.Println("half=", label)
}
package main

import "fmt"

func main() {
	var whole = 3
	half := float64(whole) / 2.0
	label := fmt.Sprintf("%.1f", half)

	fmt.Println("whole=", whole)
	fmt.Println("half=", label)
}
package main

import "fmt"

func main() {
	var whole = 10
	half := float64(whole) / 2.0
	label := fmt.Sprintf("%.1f", half)

	fmt.Println("whole=", whole)
	fmt.Println("half=", label)
}
  1. whole ← 7, half ← 3.5, label ← "3.5"

    5func main() {6  var whole→ 7 = 7 //@whole=3, 107  half→ 3.5 := float64(whole7) / 2.08  label→ "3.5" := fmt.Sprintf("%.1f", half3.5)910  fmt.Println("whole=", whole7)11  fmt.Println("half=", label"3.5")12}
    outputwhole= 7
    half= 3.5
  1. whole ← 3, half ← 1.5, label ← "1.5"

    5func main() {6  var whole→ 3 = 37  half→ 1.5 := float64(whole3) / 2.08  label→ "1.5" := fmt.Sprintf("%.1f", half1.5)910  fmt.Println("whole=", whole3)11  fmt.Println("half=", label"1.5")12}
    outputwhole= 3
    half= 1.5
  1. whole ← 10, half ← 5, label ← "5.0"

    5func main() {6  var whole→ 10 = 107  half→ 5 := float64(whole10) / 2.08  label→ "5.0" := fmt.Sprintf("%.1f", half5)910  fmt.Println("whole=", whole10)11  fmt.Println("half=", label"5.0")12}
    outputwhole= 10
    half= 5.0

Follow the Conversion

  1. whole starts at 7.
  2. float64(whole) turns it into a floating-point value.
  3. half := float64(whole) / 2.0 becomes 3.5.
  4. fmt.Sprintf("%.1f", half) keeps one digit after the decimal.
  5. The program prints whole= 7 and half= 3.5. | whole | half | label | | --- | --- | --- | | 3 | 1.5 | 1.5 | | 7 | 3.5 | 3.5 | | 10 | 5.0 | 5.0 |

Exercise: type_conversion.go

Reproduce half= 3.5, then use the pinned whole values 3 and 10 to predict each one-decimal label.