LoginSignup
2
1

More than 5 years have passed since last update.

Effective Goを読んでて気になった型変換

Posted at

ポケモンGOの公開とともにGoを勉強し始めて、今はEffective Goを読んでいるところなんですが、Interface checksの節で、以下のような変換が書いてありました。

var _ json.Marshaler = (*RawMessage)(nil)

(*RawMessage)がjson.Marshalerをimplementしてるかチェックするためのコードで、まぁそこの意味はわかるんですが、
変換ってT(value)で変換するか、value.(T)みたいにtype assertionする以外にもあるのかー、という疑問が湧いたのでspecを見てみました。

で、specのConversionsの節を見るとドンピシャの内容が書いてありました。

If the type starts with the operator * or <-, or if the type starts with the keyword func and has no result list, it must be parenthesized when necessary to avoid ambiguity:

*Point(p) // same as *(Point(p))
(*Point)(p) // p is converted to *Point

結論としては、変換先の型に*がついてると、pを*Pointに変換するのかPointに変換するのか曖昧なので、括弧を使って曖昧さを回避しようという話でした。
言われてみればなるほどなー案件。

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