5
4

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 5 years have passed since last update.

Go言語のデータ型と配列、スライス、マップ

5
Last updated at Posted at 2016-02-18

基本のデータ型

string, int, float64, bool, nil
初期値

var s string //""
var a int //0
var f bool //false

変数

func main(){
  var msg string
  msg = "hello world"
  var msg1 string = "hello world1"
  var msg2 = "hello world2" //stringは省略可能
  msg3 := "hello world3" //値と変数の紐付け
  fmt.Println(msg)
  fmt.Println(msg1)
  fmt.Println(msg2)
  fmt.Println(msg3)
  
  a, b := 1, 2 //複数宣言
  fmt.Println(a)
  fmt.Println(b)
  
  var (
    c = 1
    d = "test"
  )
}

配列

func main(){
  var a [5]int
  b := [3]int{1, 3, 5} //型の宣言と同時に値を代入
  c := [...]int{1, 3, 5, 6} //値はわかっているので指定する必要なし
  fmt.Println(a)
  fmt.Println(b)
  fmt.Println(c)
}

配列の展開

func main() {
	array1 := []int{1, 2, 3}
	array2 := []int{4, 5, 6}
	array3 := append(array1, array2...)

	fmt.Println(array1)
	fmt.Println(array2)
	fmt.Println(array3)
}
[1 2 3]
[4 5 6]
[1 2 3 4 5 6]

スライス1

func main(){
  a := [5]int{9, 8, 7, 6, 5}
  s := a[0:3]
  s[0] = 12
  fmt.Println(a)//[12 8 7 6 5]
  fmt.Println(s)//[12 8 7]
  fmt.Println(len(s))//3
  fmt.Println(cap(s))//5 0から切り出せる最大の値
}

スライス2

func main(){
  s := make([]int, 3)
  s2 := []int{1, 3, 5}
  fmt.Println(s)//[0 0 0]]
  fmt.Println(s2)//[1 3 5]
  s2 = append(s2, 10)
  fmt.Println(s2)//[1 3 5 10]
  s3 := make([]int, len(s2))
  num := copy(s3, s2)
  fmt.Println(s3)//[1 3 5 10]
  fmt.Println(num)//4
}

スライス3

func main(){
  cards := []string{newCard(), "Ace of Dia"}
  cards = append(cards, "Six of Spades")

  for i, card := range cards {
    fmt.Println(i, card)
  }
}

マップ

func main() {
  m := make(map[string]int)
  m["japan"] = 100
  m["ame"] = 200
  fmt.Println(m)
  delete(m, "japan")
  fmt.Println(m)
  m2 := map[string]int{"tokyo":1, "osaka":2}
  fmt.Println(m2)

  m3 := make(map[string]string)
  m3["japan"] = "no1"
  m3["ame"] = "no2"
  fmt.Println(m3)
  v1, ok := m3["japan"]
  fmt.Println(v1)//no1
  fmt.Println(ok)//true

  v2, ng := m3["canada"]
  fmt.Println(v2)
  fmt.Println(ng)//false
}
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?