LoginSignup
0
0

More than 1 year has passed since last update.

【自己学習】Go言語を学ぶ(7)

Posted at

公式チュートリアルから基本を学ぶ

If文

  • Go言語の if 文は、先ほどの for ループと同様に、括弧 ( ) は不要で、中括弧 { } は必要です。

サンプルコード:

package main

import (
  "fmt"
  "math"
)

func sqrt(x float64) string {
  if x < 0 {
    return sqrt(-x) + "i"
  }
  return fmt.Sprint(math.Sqrt(x))
}

func main() {
  fmt.Println(sqrt(2), sqrt(-4))
}

実行結果:1.4142135623730951 2i

If with a short statement(if文を短くした場合)

if 文は、 for のように、条件の前に、評価するための簡単な文を書くことができます。

ここで宣言された変数は、 if のスコープ内だけで有効です。

サンプルコード:math.Powでべき乗を計算

package main

import (
  "fmt"
  "math"
)

func pow(x, n, lim float64) float64 {
  if v := math.Pow(x, n); v < lim {
    return v
  }
  return lim
}

func main() {
  fmt.Println(
    pow(3, 2, 10),
    pow(3, 3, 20),
  )
}

実行結果:9 20

If and else (ifとelse)

if 文で宣言された変数は、 else ブロック内でも使うことができます。

サンプルコード:

package main

import (
  "fmt"
  "math"
)

func pow(x, n, lim float64) float64 {
  if v := math.Pow(x, n); v < lim {
    return v
  } else {
    fmt.Printf("%g >= %g\n", v, lim)
  }
  // can't use v here, though
  return lim
}

func main() {
  fmt.Println(
    pow(3, 2, 10),
    pow(3, 3, 20),
  )
}

実行結果:
27 >= 20
9 20

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