開発環境
- macOS High Sierra - Apple (OS)
- Emacs (Text Editor)
- Go (プログラミング言語)
Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 7.(Structs and Interfaces)、Exercises(No. 1315)3.を取り組んでみる。
コード(Emacs)
package main import ( "fmt" "math" ) type Circle struct { x, y, r float64 } type Rectangle struct { x1, y1, x2, y2 float64 } type Shape interface { perimeter() float64 } func (c *Circle) perimeter() float64 { return math.Pi * math.Pow(c.r, 2) } func (r *Rectangle) perimeter() float64 { a := r.x2 - r.x1 b := r.y2 - r.y1 return 2 * (math.Abs(a) + math.Abs(b)) } func main() { c1 := Circle{x: 1, y: 2, r: 1} c2 := Circle{3, 4, 5} r1 := Rectangle{x1: 1, y1: 2, x2: -1, y2: -2} r2 := Rectangle{-1, -2, 1, 2} shapes := []Shape{&c1, &c2, &r1, &r2} fmt.Println(math.Pi, math.Pow(2, 3)) for _, s := range shapes { fmt.Println(s.perimeter()) } }
入出力結果(Terminal)
$ go run sample3.go 3.141592653589793 8 3.141592653589793 78.53981633974483 12 12 $
0 コメント:
コメントを投稿