LoginSignup
2
0

More than 3 years have passed since last update.

続やさしめのGo Quiz

Last updated at Posted at 2020-12-08

問題

つぎのコードを実行するとどうなるでしょう。

package main

func hello() {
    hello := func() {
        hello := func() {
            print("hello")
        }
        hello()
    }
    hello()
}

func main() {
    hello := hello
    hello()
}

A. hello と出力される
B. hellohello と出力される
C. コンパイルエラー
D. 実行時エラー(panic)

解答

ここを開いてください

正解はAです。

3行目から定義が始まる関数hello(以下hello3)が単純に呼び出されて場合については、昨日の問題と同様です。
くせものは14行目の変数hello(以下hello14)にhello3を代入しているところですが、これは許されます。つまり15行目で実行されているのはhello14です。

この代入が許されるのは、関数名(FunctionName) は identifier であり、identifier:= の右辺にとれるものの一つだからです。
詳しくは仕様の Short variable declarationsFunction declarationsからたどっていくとよいでしょう。

2
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
2
0