0
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 1 year has passed since last update.

【Golang】ステートメントまとめ

Last updated at Posted at 2022-06-01

24 if文

 if result2 := by2(10); result2 == "ok"{
    fmt.Println("great 2")
 }

result2の値をこの式以降使用しない場合は、セミコロン;をつなげて条件式を一行で書くことができる。

25 for文

func main() {
    sum := 1
    for sum < 10 {
        sum += sum
        fmt.Println(sum)
    }
}

phpのようにfor文は書けるが、上記のように省略することもできる
初期値をforの前に定義、インクリメントは省略

26 range文

func main() {
    l := []string{"Python", "go", "Java"}

    for i := 0; i < len(l); i++{
        fmt.Println(i, l[i])
    }

    for i, v := range l{
        fmt.Println(i, v)
    }
}

スライスの値を出力する際に使用する
上のようにfor文で一つ一つ出してもいいが、下のように変数のiとvを定義してrangeで添字とバリューを出力することもできる

for _, v := range l {
		fmt.Println(v)
	}

iを使用しない場合はアンダースコアを使えば省略できる

28 defer

deferはmain関数の処理がすべて終わった後に実行される
func main() {
    defer fmt.Println("success")
    defer fmt.Println("1")
    defer fmt.Println("2")
    defer fmt.Println("3")
    fmt.Println("mail send")
}

deferが複数ある場合は下に書かれているdeferから順に実行される

34 ポインタ

package main

import "fmt"

func main() {
	var n int = 100
	fmt.Println(n)
	fmt.Println(&n)

	var p *int = &n
	fmt.Println(p)
	fmt.Println(*p)
}

// 実行結果
100
0xc0000160c8
0xc0000160c8
100

アンパサンド&を使用すると、その値を確保しているメモリを参照できる。
メモリのアドレスを格納するときはポインタ型を使用する。intの型で使用できる。
ポインタ型として定義した変数にアスタリスク
をつけることで、メモリのアドレスに格納されている値を取得することができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?