2020年2月4日火曜日

開発環境

入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 5(状態と振る舞い)、LESSON 22(Goにはクラスがないけれど)の練習問題1の解答を求めてみる。

コード

package main

import "fmt"

type coordinate struct {
 d, m, s float64
 h       rune
}

func (c coordinate) decimal() float64 {
 var sign float64
 switch c.h {
 case 'N', 'E', 'n', 'e':
  sign = 1.0
 default:
  sign = -1.0
 }
 return sign * (c.d + c.m/60 + c.s/3600)
}

type location struct {
 lat, long float64
}

func newLocation(lat, log coordinate) location {
 return location{lat.decimal(), log.decimal()}
}

type nameAndLocation struct {
 name string
 loc  location
}

func main() {
 spirit := nameAndLocation{
  name: "Spirit",
  loc: newLocation(
   coordinate{d: 14, m: 34, s: 6.2, h: 'S'},
   coordinate{175, 28, 21.5, 'E'},
  ),
 }
 opportunity := nameAndLocation{
  name: "Opportunity",
  loc: newLocation(
   coordinate{1, 56, 46.3, 'S'},
   coordinate{354, 28, 24.2, 'E'},
  ),
 }
 curiosity := nameAndLocation{
  name: "Curiosity",
  loc: newLocation(
   coordinate{4, 35, 22.2, 's'},
   coordinate{137, 26, 30.1, 'e'},
  ),
 }
 inSight := nameAndLocation{
  name: "InSight",
  loc: newLocation(
   coordinate{4, 30, 0, 'n'},
   coordinate{135, 54, 0, 'e'},
  ),
 }
 landers := []nameAndLocation{
  spirit,
  opportunity,
  curiosity,
  inSight,
 }

 for _, lander := range landers {
  fmt.Printf("%v: %v\n", lander.name, lander.loc)
 }
}

入出力結果(Zsh、PowerShell、Terminal)

% go run landing.go
Spirit: {-14.568388888888888 175.4726388888889}
Opportunity: {-1.9461944444444446 354.47338888888885}
Curiosity: {-4.5895 137.44169444444444}
InSight: {4.5 135.9}
%

0 コメント:

コメントを投稿