为什么Rust不给出一个"无条件递归";当Self::from(x)
发出警告时使用x.into()
方法发出警告?
考虑下面的例子,在铁锈操场:
struct Foo;
struct Bar;
impl From<Foo> for Bar {
fn from(x: Foo) -> Self {
x.into() // No recursion warning
}
}
fn main() {}
考虑另一个例子,显示铁锈操场中的递归警告
struct Foo;
struct Bar;
impl From<Foo> for Bar {
fn from(x: Foo) -> Self {
Self::from(x) // Shows recursion warning
}
}
fn main() {}
warning: function cannot return without recursing
--> src/main.rs:5:5
|
5 | fn from(x: Foo) -> Self {
| ^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
6 | Self::from(x)
| ------------- recursive call site
|
= note: `#[warn(unconditional_recursion)]` on by default
= help: a `loop` may express intention better if this is on purpose
该方法不是直接调用自己,而是调用另一个特性实现。碰巧trait实现会调用回第一个,但编译器不进行跨函数分析。这也不会触发警告:
fn a() { b(); }
fn b() { a(); }
fn main() {
a();
}
跨函数检查比局部函数检查更复杂,更难有效应用。这个案子还有一个悬而未决的问题。