計算機科学のブログ

you're my type - Defined Types - Defining methods

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

コード

main.go

package main

import "fmt"

type Number int

func (n Number) Add(otherNumber int) {
	fmt.Println(n, "plus", otherNumber, "is", int(n)+otherNumber)
}
func (n Number) Subtract(otherNumber int) {
	fmt.Println(n, "minusn", otherNumber, "is", int(n)-otherNumber)
}
func main() {
	ten := Number(10)
	ten.Add(4)
	ten.Subtract(5)
	four := Number(4)
	four.Add(3)
	four.Subtract(2)
}

入出力結果(Terminal, Zsh)

% go run ./main.go 
10 plus 4 is 14
10 minusn 5 is 5
4 plus 3 is 7
4 minusn 2 is 2
%