Skip to content

Instantly share code, notes, and snippets.

@c-yan
Last active August 7, 2018 11:15
Show Gist options
  • Save c-yan/451a59fed7448cdec79eb0ef33fcc9a7 to your computer and use it in GitHub Desktop.
Save c-yan/451a59fed7448cdec79eb0ef33fcc9a7 to your computer and use it in GitHub Desktop.
『ポリモーフィズムを活用するとなぜ if や switch が消えるのか?』プログラマー2年生が説明してみる。 へのコメント

https://play.golang.org/p/YEK-6IWQ6Bw https://qiita.com/Nossa/items/a93024e653ff939115c6

GO 言語版です.

package main

import (
	"fmt"
	"math"
)

type shape interface {
	area() float64
}

type triangle struct {
	base   float64
	height float64
}

type circle struct {
	radius float64
}

type rectangle struct {
	width  float64
	height float64
}

func (t triangle) area() float64 {
	return t.base * t.height / 2
}

func (c circle) area() float64 {
	return c.radius * c.radius * math.Pi
}

func (r rectangle) area() float64 {
	return r.width * r.height
}

func main() {
	shapes := []shape{
		triangle{base: 5, height: 4},
		circle{radius: 3},
		rectangle{width: 4, height: 4},
	}
	for _, shape := range shapes {
		fmt.Printf("AREA: %f\n", shape.area())
	}
}

出力結果

AREA: 10.000000
AREA: 28.274334
AREA: 16.000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment