開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 5(状態と振る舞い)、LESSON 24(インターフェイス)の練習問題の解答を求めてみる。
コード
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
)
type coordinate struct {
d, m, s float64
h rune
}
func (c coordinate) decimal() float64 {
sign := 1.0
switch c.h {
case 'S', 'W', 's', 'w':
sign = -1
}
return sign * (c.d + c.m/60 + c.s/3600)
}
func (c coordinate) String() string {
return fmt.Sprintf("%v°%v'%.1f\" %v",
c.d, c.m, c.s, strings.ToUpper(string(c.h)))
}
func (c coordinate) MarshalJSON() ([]byte, error) {
s := fmt.Sprintf(
`{"decimal":%v,"dms":"%v°%v'%.1f\" %v","degrees":%[2]v,"minutes":%[3]v,"seconds":%[4]v,"hemisphere":"%[5]v"}`,
c.decimal(), c.h, c.m, c.s, strings.ToUpper(string(c.h)),
)
return []byte(s), nil
}
type location struct {
name string
lat, long coordinate
}
func newLocation(name string, lat, long coordinate) location {
return location{name: name, lat: lat, long: long}
}
func (l location) String() string {
return fmt.Sprintf("%v is at %v, %v", l.name, l.lat, l.long)
}
func exitOnError(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func main() {
elsyiumPlanitiaLat := coordinate{4, 30, 0, 'n'}
elysiumPlanitiaLong := coordinate{135, 54, 0, 'e'}
elsyiumPlanitia := newLocation(
"Elysium Planitia",
elsyiumPlanitiaLat,
elysiumPlanitiaLong,
)
fmt.Println(elsyiumPlanitia)
bytes, err := json.Marshal(elysiumPlanitiaLong)
exitOnError(err)
fmt.Println(string(bytes))
bytes, err = json.MarshalIndent(elysiumPlanitiaLong, "", " ")
exitOnError(err)
fmt.Println(string(bytes))
bytes, err = json.MarshalIndent(elysiumPlanitiaLong, ">", " ")
exitOnError(err)
fmt.Println(string(bytes))
}
入出力結果(Zsh、PowerShell、Terminal)
% go run marshal.go
Elysium Planitia is at 4°30'0.0" N, 135°54'0.0" E
{"decimal":135.9,"dms":"101°54'0.0\" E","degrees":101,"minutes":54,"seconds":0,"hemisphere":"E"}
{
"decimal": 135.9,
"dms": "101°54'0.0\" E",
"degrees": 101,
"minutes": 54,
"seconds": 0,
"hemisphere": "E"
}
{
> "decimal": 135.9,
> "dms": "101°54'0.0\" E",
> "degrees": 101,
> "minutes": 54,
> "seconds": 0,
> "hemisphere": "E"
>}
%
0 コメント:
コメントを投稿