サンプル
package main
import "fmt"
type Person struct {
name string
age int
}
func main() {
// 宣言の後、値を代入
var person1 Person
person1.name = "Akira"
person1.age = 20
fmt.Println(person1)
// 宣言+代入
person2 := Person{age: 30, name: "Kure"}
fmt.Println(person2)
// 宣言+代入
person3 := Person{"Aki", 40}
fmt.Println(person3)
}
package main
import (
"fmt"
"encoding/json"
)
func main() {
type location struct {
Name string
Lat float64
Long float64
}
// JSON 変換するためにキーを大文字にしておく必要がある
locations := []location {
{Name: "Brandbury Landing", Lat: -4.5895, Long: 137.4417},
{Name: "Columbia Memorial Station", Lat: -14.56684, Long: 175.472636},
{Name: "Challenger Memorial Station", Lat: -1.9462, Long: 354.4734},
}
// [{Brandbury Landing -4.5895 137.4417} {Columbia Memorial Station -14.56684 175.472636} {Challenger Memorial Station -1.9462 354.4734}]
fmt.Println(locations)
b, _ := json.Marshal(locations)
// [{"Name":"Brandbury Landing","Lat":-4.5895,"Long":137.4417},{"Name":"Columbia Memorial Station","Lat":-14.56684,"Long":175.472636},{"Name":"Challenger Memorial Station","Lat":-1.9462,"Long":354.4734}]
fmt.Println(string(b))
// JSONキーを指定
type location2 struct {
Name string `json:"name"`
Lat float64 `json:"lat"`
Long float64 `json:"long"`
}
locations2 := []location2 {
{Name: "Brandbury Landing", Lat: -4.5895, Long: 137.4417},
{Name: "Columbia Memorial Station", Lat: -14.56684, Long: 175.472636},
{Name: "Challenger Memorial Station", Lat: -1.9462, Long: 354.4734},
}
// [{Brandbury Landing -4.5895 137.4417} {Columbia Memorial Station -14.56684 175.472636} {Challenger Memorial Station -1.9462 354.4734}]
fmt.Println(locations2)
c, _ := json.MarshalIndent(locations2, "", " ")
// [
// {
// "name": "Brandbury Landing",
// "lat": -4.5895,
// "long": 137.4417
// },
// {
// "name": "Columbia Memorial Station",
// "lat": -14.56684,
// "long": 175.472636
// },
// {
// "name": "Challenger Memorial Station",
// "lat": -1.9462,
// "long": 354.4734
// }
//]
fmt.Println(string(c))
}
参考
改訂2版 基礎からわかる Go言語
posted with amazlet at 20.02.15
古川 昇
シーアンドアール研究所 (2015-07-17)
売り上げランキング: 201,077
シーアンドアール研究所 (2015-07-17)
売り上げランキング: 201,077