Unit Converter
Converts temperatures between Celsius, Fahrenheit, and Kelvin using custom type aliases with explicit type conversions. Demonstrates format verbs, constants, and zero values.
package main
import "fmt"
type Celsius float64
type Fahrenheit float64
type Kelvin float64
const (
AbsoluteZeroC Celsius = -273.15
BoilingPointC Celsius = 100.0
FreezingPointC Celsius = 0.0
)
func (c Celsius) ToFahrenheit() Fahrenheit {
return Fahrenheit(c*9/5 + 32)
}
func (c Celsius) ToKelvin() Kelvin {
return Kelvin(c + 273.15)
}
func (f Fahrenheit) ToCelsius() Celsius {
return Celsius((f - 32) * 5 / 9)
}
func (k Kelvin) ToCelsius() Celsius {
return Celsius(k - 273.15)
}
func main() {
temperatures := []Celsius{AbsoluteZeroC, FreezingPointC, 37.0, BoilingPointC}
fmt.Printf("%-12s | %-12s | %-12s\n", "Celsius", "Fahrenheit", "Kelvin")
fmt.Println("-------------+--------------+-------------")
for _, c := range temperatures {
f := c.ToFahrenheit()
k := c.ToKelvin()
fmt.Printf("%8.2f °C | %8.2f °F | %8.2f K\n", c, f, k)
}
fmt.Println()
// Demonstrate explicit type conversion requirement
var unset Celsius // zero value
fmt.Printf("Zero value of Celsius: %.2f °C\n", unset)
fmt.Printf("Body temp in Kelvin: %.2f K\n", Celsius(37.0).ToKelvin())
// Convert from Fahrenheit back to Celsius
boiling := Fahrenheit(212)
fmt.Printf("%.0f °F = %.2f °C\n", boiling, boiling.ToCelsius())
}