Created
March 8, 2015 17:28
-
-
Save giwa/eb1c7554d45dd2fcc98c to your computer and use it in GitHub Desktop.
Go by Example: Interfaces ref: http://qiita.com/giwa/items/81154eca31694e849b3b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "math" | |
// 幾何学的な形の基本的なインターフェースです。 | |
type geometry interface { | |
area() float64 | |
perim() float64 | |
} | |
// 私達の例ではsquareとcircleにこのインターフェイスを実装します。 | |
type square struct { | |
width, height float64 | |
} | |
type circle struct { | |
radius float64 | |
} | |
// Goでインターフェイスを実装するためにはインターフェイスの中のすべてのメソッドを実装するだけです。ここではsquareのgeometryを実装します。 | |
func (s square) area() float64 { | |
return s.width * s.height | |
} | |
func (s square) perim() float64 { | |
return 2*s.width + 2*s.height | |
} | |
// circleへの実装です。 | |
func (c circle) area() float64 { | |
return math.Pi * c.radius * c.radius | |
} | |
func (c circle) perim() float64 { | |
return 2 * math.Pi * c.radius | |
} | |
// もし変数がインターフェイスの型であれば、定義されたインターフェイスの中のメソッドを呼ぶことができます。これは、すべての幾何学で動くようにするため、その特性を活かした幾何学の計測の関数です。 | |
func measure(g geometry) { | |
fmt.Println(g) | |
fmt.Println(g.area()) | |
fmt.Println(g.perim()) | |
} | |
func main() { | |
s := square{width: 3, height: 4} | |
c := circle{radius: 5} | |
// このcircleとsquareの構造体はgeometryのインターフェイスを実装しています。なのでこれらの構造体のインスタンスを引数として計測するために使うことができます。 | |
measure(s) | |
measure(c) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run interfaces.go | |
{3 4} | |
12 | |
14 | |
{5} | |
78.53981633974483 | |
31.41592653589793 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment