2016年2月5日金曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Go (version go1.5.3 darwin/amd64) (プログラミング言語)

Introducing Go (Caleb Doxsey (著)、O'Reilly Media)のChapter 6.(Structs and Interfaces)、Exercises 1-3.(No. 1305)を取り組んでみる。

Exercises 1-3.(No. 1305)

コード(Emacs)

package main

import ("fmt"; "math")

type Rectangle struct {
 width float64
 height float64
}

// function
func area(r Rectangle) float64 {
 return r.width * r.height
}

// method
func (r Rectangle) area() float64 {
 return r.width * r.height
}

type Animal struct {
 name string
}
type Dog struct {
 Animal
 age int
}
type Cat struct {
 animal Animal
 age int
}

func (r Rectangle) perimeter() float64 {
 return 2 * (r.width + r.height)
}

type Circle struct {
 x, y, r float64
}
func (c Circle) area() float64 {
 return c.r * c.r * math.Pi
}
func (c Circle) perimeter() float64 {
 return 2 * c.r * math.Pi
}
type Shape interface {
 area() float64
 perimeter() float64
}
type Shapes struct {
 shapes []Shape
}
func main() {
 fmt.Println("1.")
 rect := Rectangle{width:5, height:10}
 fmt.Println(area(rect))
 fmt.Println(rect.area())

 fmt.Println("2.")
 d := new(Dog)
 d.name ="dog"
 d.age = 5
 c := new(Cat)
 c.animal.name = "cat"
 c.age = 10
 fmt.Println(d.name, d.age)
 // 無名にしないと、直接アクセスできなくて、冗長になる
 fmt.Println(c.animal.name, c.age)
 
 fmt.Println("3.")
 circle := Circle{x:0, y:0, r:10}
 fmt.Println(rect.perimeter())
 fmt.Println(circle.perimeter())
 shapes := []Shape{rect, circle}
 for _, shape := range shapes {
  fmt.Println(shape.perimeter())
 }
}

入出力結果(Terminal)

$ go run main.go
1.
50
50
2.
dog 5
cat 10
3.
30
62.83185307179586
30
62.83185307179586
$

0 コメント:

コメントを投稿