LoginSignup
0
0

More than 3 years have passed since last update.

関数

Last updated at Posted at 2019-06-09

いろいろな関数の書き方

func add(x int, y int) {
    fmt.Println("add function")
    fmt.Println(x + y)
}

func main() {
    add(10, 20)
}
func add(x int, y int) int { //(x, y int)に省略可
    return x + y
}

func main() {
    r := add(100, 200)
    fmt.Println(r)
}
func add(x, y int) (int, int) {
    return x + y, x - y
}

func main() {
    r1, r2 := add(100, 200)
    fmt.Println(r1, r2)
}
func cal(price, item int) (result int) {
    result = price * item //返り値のところでresultを宣言しているので:=は使えない。再定義できない。
    return                //この関数はresultを返すというのが分かっているのでresultを省略可
}
func main() {
    r3 := cal(300, 500)
    fmt.Println(r3)
}
// func convert(price int) float64{
//  return float64(price)
// }
// このように、どういう処理をしているか明らかな場合には変数を宣言する必要はない。
func main() {
    f := func(x int) {
        fmt.Println("hoge func", x) //hoge func 1
    }
    f(1)

    func(x int) {
        fmt.Println("hoge func", x)
    }(1)
    //同じ結果
}

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

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