開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
Head First Go (Jay McGavren(著)、O'Reilly Media)のChapter 10(keep it to yourself - Encapsulation and Embedding)、Exercise(306)の解答を求めてみる。
コード
coordinates.go
package geo
import "errors"
type Coordinates struct {
latitude float64
longitude float64
}
func (c *Coordinates) Latitude() float64 {
return c.latitude
}
func (c *Coordinates) Longitude() float64 {
return c.longitude
}
func (c *Coordinates) SetLatitude(latitude float64) error {
if latitude < -90 || latitude > 90 {
return errors.New("invalid latitude")
}
c.latitude = latitude
return nil
}
func (c *Coordinates) SetLongitude(longitude float64) error {
if longitude < -180 || longitude > 180 {
return errors.New("invalid longitude")
}
c.longitude = longitude
return nil
}
sample2.go
package main
import (
"fmt"
"heafirstgo/geo"
"log"
)
func main() {
coordinates := geo.Coordinates{}
err := coordinates.SetLatitude(37.42)
if err != nil {
log.Fatal(err)
}
err = coordinates.SetLongitude(-1122.08)
if err != nil {
log.Fatal(err)
}
fmt.Println(coordinates.Latitude())
fmt.Println(coordinates.Longitude())
}
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)
$ go run sample2.go 2019/06/16 13:34:45 invalid longitude exit status 1 $
0 コメント:
コメントを投稿