LoginSignup
11
2

More than 3 years have passed since last update.

Rust 1.40.0でtuple構造体とenum variantのコンストラクタがconst fnになる

Last updated at Posted at 2019-12-17

この記事はRustその2 Advent Calendar 2019の17日目の記事です。

この記事は2019年12月17日時点のrust-lang/rust/blob/master/RELEASES.mdの内容に基づいて書かれています。

Rust 1.40.0でtuple構造体とenum variantのコンストラクタがconst fnになる

12/19にリリース予定のRust1.40.0でtuple構造体とenum variantのコンストラクタがconst fnになります。

tuple構造体のコンストラクタ

下記コードのコンパイルが通るようになります。

pub struct Point(i32, i32);

const ORIGIN: Point = {
    let constructor = Point;

    constructor(0, 0)
};

constructorは関数です。(これをなんと呼ぶべきかわからないため関数と表記しています。経緯はこの記事のコメントを確認してください)
上記のコードはconst変数の初期化ですがconst fnの中でも同じように使うことができます。

const fn origin() -> Point {
    let constructor = Point;
    constructor(0, 0)
}

enum variantのコンストラクタ

今までも可能だった

Some(0);
(Option::Some)(1);

に加えて

let f = Option::Some;
f(2);
{Option::Some}(3);
<Option<_>>::Some(5);

が可能になるそうです。

と書いてありますがプルリクエストに書いてある下記のコードのコンパイルは通りませんでした

const fn make_options() {
    // These already work because they are special cased:
    Some(0);
    (Option::Some)(1);
    // These also work now:
    let f = Option::Some;
    f(2);
    {Option::Some}(3);
    <Option<_>>::Some(5);
}

コンパイル結果

エラー内容
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/lib.rs:8:6
  |
8 |     {Option::Some}(3);
  |      ^^^^^^^^^^^^ expected (), found fn item
  |
  = note: expected type `()`
             found type `fn(_) -> std::option::Option<_> {std::option::Option::<_>::Some}`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

エラーが出ているのは8行目の

{Option::Some}(3);

の部分で

let o = {Option::Some}(3);

のように変数に代入するときには問題なくコンパイルが通ります。

おわりに

正直自分が書くコードにはあまり影響がない部分だとは思いますがconst fnでできることが増えていくことはいいことだと思います。
これからもどんどんconst fnが使いやすくなっていくと良いですね。

11
2
2

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
11
2