2
1

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修行4日目 map型、関数

Posted at

map型


package main

import "fmt"

func main() {
	m := map[string]int{"apple": 100, "banana": 200}

	// 要素全部表示
	fmt.Println(m)
	fmt.Println(m["apple"])

	// 要素追加
	m["banana"] = 300
	fmt.Println(m)
	m["new"] = 500
	fmt.Println(m)

	// ないものを取り出そうとすると0になる
	fmt.Println(m["nothing"])

	// boolean型も返す
	v, ok := m["apple"]
	fmt.Println(v, ok)

	// boolean型も返す
	v2, ok2 := m["nothing"]
	fmt.Println(v2, ok2)
}

出力

API server listening at: 127.0.0.1:4056
map[apple:100 banana:200]
100
map[apple:100 banana:300]
map[apple:100 banana:300 new:500]
0
100 true
0 false
Process exiting with code: 0

byte型


package main

import "fmt"

func main() {
	b := []byte{72, 73}
	fmt.Println(b)
	// stringにキャスト ASCIIコード
	fmt.Println(string(b))

	c := []byte("HI")
	fmt.Println(c)
	fmt.Println(string(c))
}
[72 73]
HI
[72 73]
HI

関数


package main

import "fmt"

// 関数
func add(x int, y int) {
	fmt.Println("add function")
	fmt.Println(x + y)
}

func main() {
	add(10, 20)
}
add function
30

複数の戻り値をInt型で返す

package main

import "fmt"

// 返り値を右にかく
func add(x int, y int) (int, int) {
	return x + y, x - y
}

func main() {
	r1, r2 := add(10, 20)
	fmt.Println(r1, r2)
}

30 -10
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?