LoginSignup
1
0

More than 3 years have passed since last update.

if文

Last updated at Posted at 2019-06-15

if

func main() {
    num := 10
    if num%2 == 0 {
        fmt.Println("by 2")
    }
}

if else

func main() {
    num := 11
    if num%2 == 0 {
        fmt.Println("by 2")
    } else {
        fmt.Println("else")
    }
}

else if

func main() {
    num := 9
    if num%2 == 0 {
        fmt.Println("by 2")
    } else if num%3 == 0 {
        fmt.Println("by3")
    } else {
        fmt.Println("else")
    }
}

&& ||

func main() {
    x, y := 10, 10
    if x == 10 && y == 10 {
        fmt.Println("&&")
    }
}
func main() {
    x, y := 11, 22
    if x == 10 && y == 10 {
        fmt.Println("&&")
    } else if x == 10 || y == 22 {
        fmt.Println("||")
    }
}

関数を使った書き方

func by2(num int) string {
    if num%2 == 0 {
        return "ok"
    } else {
        return "hoge"
    }
}

func main() {
    result := by2(10)
    if result == "ok" {
        fmt.Println("nice!")
    }
}

main関数内をもっと簡単に書くこともできる

if result := by2(10); result =="ok"{
    fmt.Println("nice!")
}

ただし、この書き方だとif文の中でしかresultを使うことができないので注意したい。

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

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