trying_out_go/cmd/playground/fuel.go

67 lines
1.6 KiB
Go

// part of chapter 9
package main
import "fmt"
type Liters float64
func (l Liters) String() string {
return fmt.Sprintf("%0.2f L", l)
}
type Gallons float64
func (g Gallons) String() string {
return fmt.Sprintf("%0.2f gal", g)
}
type Milliliters float64
func (m Milliliters) String() string {
return fmt.Sprintf("%0.2f mL", m)
}
func (l Liters) ToGallons() Gallons {
return Gallons(l * 0.264)
}
func (m Milliliters) ToGallons() Gallons {
return Gallons(m * 0.000264)
}
func (g Gallons) ToLiters() Liters {
return Liters(g * 3.785)
}
func (g Gallons) ToMilliliters() Milliliters {
return Milliliters(g * 3785.41)
}
func fuel() {
// long version
//var carFuel Gallons
//var busFuel Liters
//carFuel = Gallons(10.0)
//busFuel = Liters(240.0)
// short version
soda := Liters(2)
fmt.Printf("%0.0f liters equals %0.3f gallons\n", soda, soda.ToGallons())
water := Milliliters(500)
fmt.Printf("%0.0f milliliters equals %0.3f gallons \n", water, water.ToGallons())
//carFuel := Gallons(10.0)
//busFuel := Liters(240.0)
//
////if you want to convert between types, save variable with correct calculation
//carFuel += ToGallons(Liters(40.0))
//busFuel += ToLiters(Gallons(30.0))
//fmt.Printf("Car Fuel: %0.1f gallons\n", carFuel)
//fmt.Printf("Bus Fuel: %0.1f liters\n", busFuel)
milk := Gallons(2)
fmt.Printf("%0.0f gallons equals %0.3f liters\n", milk, milk.ToLiters())
fmt.Printf("%0.0f gallons equals %0.3f milliliters\n", milk, milk.ToMilliliters())
fmt.Println(Gallons(12.09285934))
fmt.Println(Liters(12.09285934))
fmt.Println(Milliliters(12.09285934))
}