Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- )
- // 歩く機能、食べる機能を持っているものは動物である。
- type Animal interface {
- Walk()
- Eat()
- }
- // Animalインターフェースに定義されているメソッドを満たしているので、
- // Animalインターフェースを実装していることになる。
- type Dog struct{}
- // 歩く
- func (d Dog) Walk() {
- fmt.Println("Dog's walk.")
- }
- // 食べる
- func (d Dog) Eat() {
- fmt.Println("Dog's eat.")
- }
- // Animalインターフェースに定義されているメソッドを満たしているので、
- // Animalインターフェースを実装していることになる。
- // インターフェースに定義されていないメソッド(Work)を持っているがOK
- type Human struct{}
- // 歩く
- func (h Human) Walk() {
- fmt.Println("Human's walk.")
- }
- // 食べる
- func (h Human) Eat() {
- fmt.Println("Human's eat.")
- }
- // 働く
- func (h Human) Work() {
- fmt.Println("Human's work.")
- }
- // Animalインターフェースに定義されているメソッドを満たしていないので、
- // Animalインターフェースを実装していない。
- type Robot struct{}
- // 働く
- func (r Robot) Work() {
- fmt.Println("Robot's work.")
- }
- func main() {
- // animal interface に Dog を実装
- var dog Animal = Dog{}
- dog.Walk()
- dog.Eat()
- // animal interface に Human を実装
- var human Animal = Human{}
- human.Walk()
- human.Eat()
- // animal interface に Robot を実装
- // コンパイルエラー: "Robot does not implement Animal"
- // var robot Animal = Robot{}
- }
Add Comment
Please, Sign In to add comment