1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】構造体サンプルメモ

Last updated at Posted at 2020-02-15

サンプル

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言語
古川 昇
シーアンドアール研究所 (2015-07-17)
売り上げランキング: 201,077
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?