2018年8月24日金曜日

開発環境

  • macOS High Sierra - Apple (OS)
  • Emacs (Text Editor)
  • Go (プログラミング言語)

Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 7.(Structs and Interfaces)、Exercises(No. 1315)2.を取り組んでみる。

コード(Emacs)

package main

import "fmt"

type Animal struct {
 name           string
 weight, height float64
}
type Voice interface {
 speak()
}
type Dog struct {
 Animal
}

func (dog *Dog) speak() {
 fmt.Println("ワンワン!")
}

type Cat struct {
 Animal
}

func (cat *Cat) speak() {
 fmt.Println("にゃーにゃー")
}
func speak(voices ...Voice) {
 for _, voice := range voices {
  voice.speak()
 }
}
func main() {
 dog := Dog{}
 cat := Cat{}

 dog.name = "dog1"
 dog.weight = 10
 dog.height = 20

 cat.name = "cat1"
 cat.weight = 30
 cat.height = 40
 fmt.Println(dog)
 fmt.Println(cat)

 speak(&dog, &cat)
}

入出力結果(Terminal)

$ go run sample2.go
{{dog1 10 20}}
{{cat1 30 40}}
ワンワン!
にゃーにゃー
$

0 コメント:

コメントを投稿