LoginSignup
0
0

More than 3 years have passed since last update.

自分のためにまとめるGoの基礎

Last updated at Posted at 2019-10-08

変数宣言

// 宣言は :=
a := 1
// 再代入は =
a = 2
複数の変数バージョン
// 宣言は :=
s,t := 10, 20 
// 再代入は =
s,t = 11, 21
// 複数の変数の内、1つでも初期化があるばあいは :=
t,r := 22, 30

array

要素数固定のいつもの配列
a := [3]int{} // [0 0 0]
b := [3]int{1} // [1 0 0]
c := [3]int{1, 2, 3} // [1 2 3]
d := [2]int{1, 2, 3} // array index 2 out of bounds [0:2]

// 要素数を自動で数えてくれる書き方。スライスではない。
e := [...]string{1, 2, 3} // [1 2 3]
arrayを引数に使うときは要素数も一致させなきゃダメ
func main(){
    a := [1]string{"a"}
    echo_(slice|array1|array2)(a)//各メソッドを呼び出してみる
}

func echo_slice(strs []string) {
    fmt.Println(strs)
}
// cannot use a (type [1]string) as type []string in argument to echo_slice

func echo_array1(strs [1]string) {
    fmt.Println(strs)
}
// [a]

func echo_array2(strs [2]string) {
    fmt.Println(strs)
}
// cannot use a (type [1]string) as type [2]string in argument to echo_array2

slice

a := []int{} // []
b := []int{1, 2, 3} // [1 2 3]

// 初期状態で要素を持たせたい場合はmakeを使う
c := make([]string, 2) // [0 0] 
// 第3引数はcapacity
d := make([]string, 2, 5) // [0 0] 
要素の追加とcapacityの増加
a := []int{}
fmt.Println(len(a), cap(a), a)

for _, i := range [10]int{} {
    a = append(a, i)
    fmt.Println(len(a), cap(a),  a)
}
// --------------
0 0 []
1 1 [0]
2 2 [0 0]
3 4 [0 0 0]
4 4 [0 0 0 0]
5 8 [0 0 0 0 0]
6 8 [0 0 0 0 0 0]
7 8 [0 0 0 0 0 0 0]
8 8 [0 0 0 0 0 0 0 0]
9 16 [0 0 0 0 0 0 0 0 0]
10 16 [0 0 0 0 0 0 0 0 0 0]
要素の追加とcapacityの増加_makeの場合
a := make([]int,1,3)
fmt.Println(len(a), cap(a), a)

for _, i := range [10]int{} {
    a = append(a, i)
    fmt.Println(len(a), cap(a),  a)
}
//---------
0 3 []
1 3 [0]
2 3 [0 0]
3 3 [0 0 0]
4 6 [0 0 0 0]
5 6 [0 0 0 0 0]
6 6 [0 0 0 0 0 0]
7 12 [0 0 0 0 0 0 0]
8 12 [0 0 0 0 0 0 0 0]
9 12 [0 0 0 0 0 0 0 0 0]
10 12 [0 0 0 0 0 0 0 0 0 0]

if文

丸カッコがいらない
if a == 1 {
  println(1)
} else if a == 2 {
  println(2)
} else {
  println("else")
}

for文

配列のfor
for index, value in range list {
  println(index, value)
}

// indexいらない場合
for _, value in range list {
  println(value)
}

0
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
0
0