計算機科学のブログ

you're my type - Defined Types - methods, Liters and Milliliters

Head First GoJay McGavren(著)、O’Reilly Media)の Chapter 9(you’re my type - Defined Types)、p.284(Exercise)の解答を求めてみる。

コード

main.go

package main

import "fmt"

type Liters float64
type Milliliters float64
type Gallons float64

func (l Liters) ToMilliliters() Milliliters {
	return Milliliters(l * 1000)
}
func (m Milliliters) ToLiters() Liters {
	return Liters(m / 1000)
}
func main() {
	l := Liters(3)
	fmt.Printf("%0.1f liters is %0.1f milliliters\n", l, l.ToMilliliters())
	ml := Milliliters(500)
	fmt.Printf("%0.1f milliliters is %0.1f liters\n", ml, ml.ToLiters())
}

入出力結果(Terminal, Zsh)

% go run ./main.go 
3.0 liters is 3000.0 milliliters
500.0 milliliters is 0.5 liters
%