コア型の廃止
Go 1.25が2025年8月にリリースされる予定ですが,コア型が廃止されるそうです(なんと!).
Goodbye core types - Hello Go as we know and love it!
公式ドキュメントを引用しながら見ていきましょう(この後はほぼ和訳です).
コア型の定義
コア型は,Go 1.18でジェネリクスと共に導入された概念です.Language Specification(1.25になったらリンク見られなくなるかも)において,コア型は次のように定義されています.
Each non-interface type T has a core type, which is the same as the underlying type of T.
An interface T has a core type if one of the following conditions is satisfied:
There is a single type U which is the underlying type of all types in the type set of T; or the type set of T contains only channel types with identical element type E, and all directional channels have the same direction. No other interfaces have a core type.
The core type of an interface is, depending on the condition that is satisfied, either:
the type U; or the type chan E if T contains only bidirectional channels, or the type chan<- E or <-chan E depending on the direction of the directional channels present. By definition, a core type is never a defined type, type parameter, or interface type.
1つずつ見ていきましょう.基底型については,Goの基底型についてをご覧いただけると幸いです.
Each non-interface type T has a core type, which is the same as the underlying type of T.
非インターフェース型のコア型は,その型の基底型と同じです.
An interface T has a core type if one of the following conditions is satisfied:
インターフェースTがコア型を持つのは,以下の条件のいずれかが満たされる場合です:
There is a single type U which is the underlying type of all types in the type set of T; or
型集合内の全ての型が同じ基底型Uを持つ場合
type MyString string
type StringLike interface {
string | MyString // 基底型がstringのみ → コア型: string
}
the type set of T contains only channel types with identical element type E, and all directional channels have the same direction.
型集合が同じ要素型Eのチャネル型のみを含み,方向性チャネルが同じ方向の場合
// 同じ方向性のチャネル → コア型あり
type ReadOnlyIntChan interface {
<-chan int | <-chan int // コア型: <-chan int
}
// 異なる方向性のチャネル → コア型なし
type MixedIntChan interface {
chan int | <-chan int // 方向性が異なる → コア型なし
}
// 異なる要素型 → コア型なし
type MixedChan interface {
chan int | chan string // 要素型が異なる → コア型なし
}
No other interfaces have a core type.
それ以外のインターフェースはコア型を持ちません.
type Mixed interface {
~int | ~string // 基底型が異なる → コア型なし
}
By definition, a core type is never a defined type, type parameter, or interface type.
定義から,コア型は決して定義型,型パラメータ,インターフェース型ではありません.
廃止理由と廃止後
問題
廃止理由は主に2つあります.1つはわかりにくさです.これはそうでもないのですが,もう一方が少し厄介です.コア型による制約は必要以上に厳格で,本来可能であるべき操作を禁止していました.次のinterfaceを考えてみましょう.
type Constraint interface {
~[]byte | ~string
Hash() uint64
}
これのコア型はなんでしょうか?~[]byte
と~string
は異なる基底型を持つため,このインターフェースにはコア型がありません.そのため,以下のような直感的に可能であるべき操作がコンパイルエラーになっていました:
func at[P Constraint](x P, i int) byte {
return x[i] // エラー
}
廃止後の仕様
Go 1.25では,コア型の概念が完全に除去されます:
- 仕様書の簡素化: コア型の説明が不要になり,Go 1.18以前のシンプルな記述に戻る
- エラーメッセージの改善: 「コア型がない」ではなく「この操作はサポートされていない」のような具体的なメッセージに
- 制限の緩和: 今まで禁止されていた一部の操作が可能になる(例:
~[]byte | ~string
のような制約でのスライス操作) - 互換性: コア型がなくなっても,既存のコードは何も変わりません.そしてこれからは,今までできなかった直感的な操作ができるようになります.