LoginSignup
3
1

More than 3 years have passed since last update.

go修行5日目 if文とか

Posted at

クロージャー


package main

import "fmt"

// インクリメント
func incrementGenenrator() func() int {
    x := 0
    return func() int {
        x++
        return x
    }
}

// 円の面積
func circleArea(pi float64) func(radius float64) float64 {
    return func(radius float64) float64 {
        return pi * radius * radius
    }
}

func main() {
    counter := incrementGenenrator()
    fmt.Println(counter())
    fmt.Println(counter())
    fmt.Println(counter())

    c1 := circleArea(3.14)
    fmt.Println(c1(2))

    c2 := circleArea(3)
    fmt.Println(c2(2))
}

1
2
3
12.56
12

可変長引数


package main

import "fmt"

// func foo(param1, param2 int) とするとfoo(10, 20)の形でしか呼べない
func foo(params ...int) {
    fmt.Println(len(params), params)

    // forの中でひとつひとつ呼ぶ
    for _, param := range params {
        fmt.Println(param)
    }
}

func main() {
    foo()
    foo(10, 20)
    foo(10, 20, 30)

    s := []int{1, 2, 3}
    fmt.Println(s)

    foo(s...)
}

0 []
2 [10 20]
10
20
3 [10 20 30]
10
20
30
[1 2 3]
3 [1 2 3]
1
2
3

if文


package main

import "fmt"

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

    // and条件 両方いっちしてTrue
    x, y := 10, 12
    if x == 10 && y == 10 {
        fmt.Println("&&")
    }

    // or条件 どちらか一致していればTrue
    if x == 10 || y == 10 {
        fmt.Println("&&")
    }
}
by 3
&&

関数を使う


package main

import "fmt"

// 0で割り切れればOK関数
func by2(num int) string {
    if num%2 == 0 {
        return "ok"
    } else {
        return "no"
    }
}

func main() {
    result := by2(10)

    if result == "ok" {
        fmt.Println("Great")
    }

    // 1行で書く場合
    if result2 := by2(10); result2 == "ok" {
        fmt.Println("Great 2")
    }
}
Great
Great 2
3
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
3
1