5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go by Example: Interfaces

5
Last updated at Posted at 2015-03-08

(この記事は Go by Example: Interfaces を翻訳したものです。)

インターフェイスはメソッドの名前が付けられた集合体です。

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)
}
$ go run interfaces.go
{3 4}
12
14
{5}
78.53981633974483
31.41592653589793

Goのインターフェイスについてもっと学びたい場合はこちらの素晴らしいブログをチェックしてみてください。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?