5
0

More than 5 years have passed since last update.

golangでinterfaceを実装してみる

Posted at

はじめに

この記事はLinkbal Advent Calendar 2018の15日目の記事です。
何を書くか悩んだのですが、最近golangでinterfaceの実装をする機会があり、ちょっと調べたことがあったので、ここへ記事にすることにしました。

実装する内容

  • 図形の面積を計算するものです。(例は三角形と長方形のみ)
  • 三角形と長方形の構造体を定義します。
  • interface(Calculator)には、面積を計算するメソッド(calculate)を定義し、定義した構造体のメソッドとして実装します。

コード

sample.go
ackage main

import "fmt"

// 計算メソッドを定義するinterface
type Calculator interface {
    calculate() int
}

// 三角形の構造体
type triangle struct {
    base, height int
}

// 長方形の構造体
type rectangle struct {
    height, width int
}

// 三角形の面積を計算する
func (t triangle) calculate() int {
    return t.base * t.height / 2
}

// 長方形の面積を計算する
func (r rectangle) calculate() int {
    return r.height * r.width
}

// Calculator typeを引数として各構造体の計算メソッドを呼び出す
func calculate(calc Calculator) int {
    return calc.calculate()
}

func main() {
    // 初期化
    t := triangle{base: 10, height: 10}
    r := rectangle{height: 10, width: 10}

    // 計算
    fmt.Println("triangle", t.calculate())
    fmt.Println("rectangle", r.calculate())

    // 同じinterface(Calculator)を実装しているので
    // 同じtypeで扱うことができる
    calcSlice := []Calculator{t, r}
    for _, c := range calcSlice {

        // switchで元のtypeに戻せる
        switch v := c.(type) {
        case triangle:
            fmt.Printf("%T", v)
        case rectangle:
            fmt.Printf("%T", v)
        }

        fmt.Println(c.calculate())
    }

    //構造体を直接して、計算を実行する
    fmt.Println("triangle", calculate(t))
    fmt.Println("rectangle", calculate(r))
}

実行結果

triangle 50
rectangle 100
---------------------------
main.triangle50
main.rectangle100
---------------------------
triangle 50
rectangle 100

おわりに

いかがでしたでしょうか。golangは書き方シンプルでわかりやすいですね。
弊社ではエンジニア採用を強化しております。
golangの他に、RubyやPython、PHPなども利用しています。
ご興味ある方は、ぜひこちらからお問い合わせください。こちら

5
0
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
0