LoginSignup
2
1

More than 3 years have passed since last update.

Go Quiz: len と定数

Last updated at Posted at 2020-12-14

以下のコードはコンパイル可能でしょうか?

package main

func main() {
    foo := [2]int{1, 2}
    const foolen = len(foo)
    println(foolen)
}
  1. コンパイルできる
  2. コンパイルできない

回答と解説
正解は「1. コンパイルできる」です。定数値はコンパイル時に決まる値のみが使えます (コンパイル時に決まるにも関わらず使えない例もあります)。配列に対する len 関数の結果はコンパイル時に決まり、また定数値に使えるようです。もちろん、配列ではなくスライスに対する len 関数の結果は、コンパイル時には決まらないので使えません。ちなみにですが、今後定数に使える値が Go 1.x の間に増えるかと言うと微妙で、後方互換性の問題 () もあり、なかなか難しいと思われます。

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