開発環境
- 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 21(構造体)の練習問題の解答を求めてみる。
コード
package main
import (
"encoding/json"
"fmt"
"os"
)
type location struct {
Name string `json:"name"`
Lat float64 `json:"latitude"`
Long float64 `json:"longitude"`
}
func exitOnError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
func main() {
locations := []location{
{Name: "Bradbury Landing", Lat: -4.5895, Long: 137.4417},
{Name: "Columbia Memorial Station", Lat: -14.5684, Long: 175.472636},
{Name: "Challenger Memorial Station", Lat: -19.462, Long: 354.4734},
}
bytes, err := json.Marshal(locations)
exitOnError(err)
fmt.Println(string(bytes))
prefixes := []string{"", ">"}
for _, prefix := range prefixes {
fmt.Println("prefix", prefix)
bytes, err = json.MarshalIndent(locations, prefix, " ")
exitOnError(err)
fmt.Println(string(bytes))
}
}
入出力結果(Zsh、PowerShell、Terminal)
% go run ./landing.go
[{"name":"Bradbury Landing","latitude":-4.5895,"longitude":137.4417},{"name":"Columbia Memorial Station","latitude":-14.5684,"longitude":175.472636},{"name":"Challenger Memorial Station","latitude":-19.462,"longitude":354.4734}]
prefix
[
{
"name": "Bradbury Landing",
"latitude": -4.5895,
"longitude": 137.4417
},
{
"name": "Columbia Memorial Station",
"latitude": -14.5684,
"longitude": 175.472636
},
{
"name": "Challenger Memorial Station",
"latitude": -19.462,
"longitude": 354.4734
}
]
prefix >
[
> {
> "name": "Bradbury Landing",
> "latitude": -4.5895,
> "longitude": 137.4417
> },
> {
> "name": "Columbia Memorial Station",
> "latitude": -14.5684,
> "longitude": 175.472636
> },
> {
> "name": "Challenger Memorial Station",
> "latitude": -19.462,
> "longitude": 354.4734
> }
>]
%
0 コメント:
コメントを投稿