Rust 1.82でconst fn内での不動小数点演算が可能になった
ついにconst_fn_floating_point_arithmetic
が安定化されconst fn
内での浮動小数点演算が可能になりました。
おそらく全Rustaceanが待ち望んでいた機能だと思います。
const fn foo(a: f32, b: f32) -> f32 {
a + b
}
こういうコードがstable環境で書けるようになりました。
使用可能な関数
記事を書いている時点で使用できる関数は
{float}::is_infinite
{float}::is_finite
{float}::is_subnormal
{float}::is_normal
{float}::classify
{float}::is_sign_positive
{float}::is_sign_negative
{float}::to_bits
{float}::from_bits
{float}::to_be_bytes
{float}::to_le_bytes
{float}::to_ne_bytes
{float}::from_be_bytes
{float}::from_le_bytes
{float}::from_ne_bytes
です。
const genericsの引数に浮動小数点型を使うことができなくもないようになった
to_bits
が使用できるので下記のように結果を整数型に代入しておけばコンパイルは通ります。
struct Type<const Value: u32>;
const V: u32 = 1.0_f32.to_bits() ;
type OneF32Type = Type<V>;
使い所あったら教えてください。
おわりに
待ちに待った機能が安定化されてとても幸せな年末を迎えられました。
コンパイル時に計算できるものが増えるのは良いことです。