在带有模板元编程的 C++ 中,您可以通过这种方式轻松地在编译时计算斐波那契数列。
template<int N>
constexpr int fibonacci() {return fibonacci<N-1>() + fibonacci<N-2>(); }
template<>
constexpr int fibonacci<1>() { return 1; }
template<>
constexpr int fibonacci<0>() { return 0; }
Run Code Online (Sandbox Code Playgroud)
但是在 rust 中,据我所知,你不能只通过泛型传递一个常量,我也知道有时 rust 会将一些函数优化为汇编代码中的常量。示例:https : //rosettacode.org/wiki/Compile-time_calculation#Rust
但是问题的常规递归方法并没有优化为常数。
fn fibo(n: i32) -> i32 {
match n {
0 => 0,
1 => 1,
n => fibo(n - 1) + fibo(n - 2),
}
}
// Call it with
fibo(45); // It takes around 5 secs, calculated at runtime
Run Code Online (Sandbox Code Playgroud)
好的,到目前为止,我无法理解只是编译器不知道如何优化它,但是我找到了一种方法可以在编译时使用迭代器进行计算!
struct …Run Code Online (Sandbox Code Playgroud)