LoginSignup
9
5

More than 3 years have passed since last update.

goステートメントのgo func() {} ()の最後の丸括弧()が何かわからなかったのでメモ

Last updated at Posted at 2019-06-16

以下のようなコードの中にある go func() {} () の最後の丸括弧 () がついている理由がわからなかったので調べた。
deferでも同じかもしれない。

goroutine.go
package main

import (
    "fmt"
    "time"
)

func main() {
    go func() {
        fmt.Println("goroutine")
    }() // この丸括弧()の意味がわからなかった
    time.Sleep(time.Second)
}

ドキュメント には 関数を呼び出すために必要。 とあった。
最初どういうことかわからなかったけど、スターティングGo言語を読んで、無名関数が利用されているとわかった。

func() {
        fmt.Println("goroutine")
}

が無名関数で、この無名関数をgo文で呼び出す、ということで最後に () をつけている...んだと思う。

定義した関数を利用する形に書き直すと以下になる。

goroutine.go
package main

import (
    "fmt"
    "time"
)

func f() {
    fmt.Println("goroutine")
}

func main() {
    go f()
    time.Sleep(time.Second)
}

参考

9
5
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
9
5