Skip to content

Instantly share code, notes, and snippets.

@ordovician
Last active October 3, 2018 23:23
Show Gist options
  • Save ordovician/9515607 to your computer and use it in GitHub Desktop.
Save ordovician/9515607 to your computer and use it in GitHub Desktop.
[Custom number types in Go] Shows how you can utilize the fact that using the keyword "type" in Go create a new type unlike typedef in C. Allows us work with numbers without mixing up the units.
package main
import (
"fmt"
)
type Celsius float64
// Implement Stringer interface, used by %s in Printf
func (deg Celsius) String() string {
return fmt.Sprintf("%.1f °C", float64(deg))
}
// Convert celisus to fahrenheit
func (deg Celsius) Fahrenheit() Fahrenheit {
return Fahrenheit(float64(deg) * (9.0/5.0) + 32.0)
}
type Fahrenheit float64
// Implement Stringer interface, used by %s in Printf
func (deg Fahrenheit) String() string {
return fmt.Sprintf("%.1f °F", float64(deg))
}
// Convert fahrenheit to celisus
func (deg Fahrenheit) Celsius() Celsius {
return Celsius((float64(deg) - 32.0) * (5.0/9.0))
}
func main() {
var bodyTemp Celsius = 37
fmt.Printf("Body temprature is %s or %s\n", bodyTemp, bodyTemp.Fahrenheit())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment