LoginSignup
10
5

More than 3 years have passed since last update.

Rustのrecursion_limit

Posted at

はじめに

Rustで非常にネストの深いstruct/enum(例えば大規模な抽象構文木とか)を書いていると以下のようなコンパイルエラーが出ることがあります。
(実のところ再帰的なマクロを書いて失敗するとよく出るエラーなのですが、特にマクロを書いてなくても出るよ、という話です)

error: reached the recursion limit while instantiating `...`

この記事ではこのエラーの理由と解決方法を書きます。

何のエラーか

Rustコンパイラにはrecursion_limitという制限値があります。

The recursion_limit attribute

The recursion_limit attribute may be applied at the crate level to set the maximum depth for potentially infinitely-recursive compile-time operations like macro expansion or auto-dereference. It uses the MetaNameValueStr syntax to specify the recursion depth.

要するに「コンパイル時の処理(マクロの展開やDerefの自動追加)の際に無限再帰にならないよう最大値を設けている」ということで、これに引っかかったときに出るのが冒頭のエラーです。

単にstruct/enumのネストが深いだけなら特に関係ないのですが、例えば#[derive(Debug)]などを付けるとこのマクロの展開時に引っかかります。

現在のデフォルト値は64のようです。

解決方法

以下のように制限値を増やすことができます。

#![recursion_limit = "128"]

このアトリビュートはクレートレベルアトリビュートとなっていて、クレートのトップレベルでしか宣言できません。lib.rsmain.rsに書けばOKです。

10
5
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
10
5