Search⌘ K

Solution Review: Temperature Conversion

Understand how to use Go's type aliases to represent Celsius and Fahrenheit temperature types. Learn to write a conversion function applying the standard formula and practice calling it in a main program. This lesson helps build foundational skills in Go function creation and type management.

We'll cover the following...
Go (1.6.2)
package main
import (
"fmt"
)
// aliasing type
type Celsius float32
type Fahrenheit float32
// Function to convert celsius to fahrenheit
func toFahrenheit(t Celsius) Fahrenheit {
return Fahrenheit((t*9/5 )+ 32)
}
func main() {
var tempCelsius Celsius = 100
tempFahr := toFahrenheit(tempCelsius) // function call
fmt.Printf("%f ˚C is equal to %f ˚F",tempCelsius,tempFahr)
}
  • Lines 7-8: We aliased the types of the temperature, i.e., float32 to Celsius and Fahrenheit. At line 7, we alias the type float 32 by giving the name Celsius. We need another type called Fahrenheit, ...