2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

const fnで浮動小数点演算が可能になった

Last updated at Posted at 2024-12-13

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>;

使い所あったら教えてください。

おわりに

待ちに待った機能が安定化されてとても幸せな年末を迎えられました。
コンパイル時に計算できるものが増えるのは良いことです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?