https://ravineport.hatenablog.com/entry/2022/10/14/203939
Go言語デビューしました!🎉 シンプルなのもあってすぐに馴染むことができています。Goよいですね!
さてさて今回はGoを書いていて「これできるんだ」「これはコンパイルエラーなんだ」となったところをGoの仕様などを見ながら(できればそのwhyまで)理解したいと思います。 Go 1.18時点での記事です。
例えばこんなのがあったとして
const Ten = 10
type User struct {
age *int
}
以下のコンパイルが通りません。
func main() {
user := User{
&Ten, // コンパイル通らない🤔
}
fmt.Println(user)
}
エラーメッセージを見てみると
invalid operation: cannot take address of Ten (constant 10 of type Age)
とのこと。constのアドレスを取ることはできないらしい。
&
オペレーターに関する仕様を見てみます。どうやらここが該当していそうです。
The Go Programming Language Specification - The Go Programming Language
The operand must be addressable , that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array.
たしかに&
オペレーターを取ることのできるオペランドにconstantsはいないですね。constantは変数(variable)ではないことに注意ですね。
ここに答えがありそうです。
Taking address of string literal
リンク先はstring
の例ですがint
もリテラルという意味では同じ、かつconstはリテラルで表現されるものなので同様のことが言えそうです。