Guest User

Untitled

a guest
Jan 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. // 歩く機能、食べる機能を持っているものは動物である。
  8. type Animal interface {
  9. Walk()
  10. Eat()
  11. }
  12.  
  13. // Animalインターフェースに定義されているメソッドを満たしているので、
  14. // Animalインターフェースを実装していることになる。
  15. type Dog struct{}
  16.  
  17. // 歩く
  18. func (d Dog) Walk() {
  19. fmt.Println("Dog's walk.")
  20. }
  21.  
  22. // 食べる
  23. func (d Dog) Eat() {
  24. fmt.Println("Dog's eat.")
  25. }
  26.  
  27. // Animalインターフェースに定義されているメソッドを満たしているので、
  28. // Animalインターフェースを実装していることになる。
  29. // インターフェースに定義されていないメソッド(Work)を持っているがOK
  30. type Human struct{}
  31.  
  32. // 歩く
  33. func (h Human) Walk() {
  34. fmt.Println("Human's walk.")
  35. }
  36.  
  37. // 食べる
  38. func (h Human) Eat() {
  39. fmt.Println("Human's eat.")
  40. }
  41.  
  42. // 働く
  43. func (h Human) Work() {
  44. fmt.Println("Human's work.")
  45. }
  46.  
  47. // Animalインターフェースに定義されているメソッドを満たしていないので、
  48. // Animalインターフェースを実装していない。
  49. type Robot struct{}
  50.  
  51. // 働く
  52. func (r Robot) Work() {
  53. fmt.Println("Robot's work.")
  54. }
  55.  
  56. func main() {
  57. // animal interface に Dog を実装
  58. var dog Animal = Dog{}
  59. dog.Walk()
  60. dog.Eat()
  61.  
  62. // animal interface に Human を実装
  63. var human Animal = Human{}
  64. human.Walk()
  65. human.Eat()
  66.  
  67. // animal interface に Robot を実装
  68. // コンパイルエラー: "Robot does not implement Animal"
  69. // var robot Animal = Robot{}
  70. }
Add Comment
Please, Sign In to add comment