Rust 递归型困难
此代码是更复杂代码的简化,用于隔离问题:Rust 递归型困难,rust,Rust,此代码是更复杂代码的简化,用于隔离问题: use std::marker::PhantomData; pub trait ExtWrite { fn write_end<W>(&mut self, &mut W); } pub struct ST; impl ExtWrite for ST { fn write_end<W>(&mut self, _: &mut W) {} } struct MCW<'a, '
use std::marker::PhantomData;
pub trait ExtWrite {
fn write_end<W>(&mut self, &mut W);
}
pub struct ST;
impl ExtWrite for ST {
fn write_end<W>(&mut self, _: &mut W) {}
}
struct MCW<'a, 'b, W: 'a, EW: 'b + ExtWrite>(&'a mut W, &'b mut [EW]);
impl<'a, 'b, W: 'a, EW: 'b + ExtWrite> MCW<'a, 'b, W, EW> {
fn write_end_all(&mut self) {
if let Some((f, last)) = self.1.split_first_mut() {
let mut el = MCW(self.0, last);
f.write_end(&mut el);
// do on current el.write_end();
}
}
}
pub fn rec_test() {
let mut buff = ();
let v: Vec<TSW<ST>> = Vec::new();
let mut el: TSW<ST> = TSW(Box::new(v), PhantomData);
el.write_end(&mut buff);
}
pub struct TSW<E: ExtWrite>(Box<Vec<TSW<E>>>, PhantomData<E>);
impl<E: ExtWrite> ExtWrite for TSW<E> {
fn write_end<W>(&mut self, w: &mut W) {
let mut el = MCW(w, &mut self.0[..]);
el.write_end_all();
}
}
fn main() {}
导致:
错误:实例化'rec:'时达到递归限制:`
--> :14:1
|
14 | fn记录(b:bool,w:w){
| ^
在这种情况下,它的行为是正确的,但在我之前的案例中,我不知道如何进行这种更改:
struct IntSt<'a, W: 'a>(&'a W);
pub fn comp_err() {
let w: u8 = 0;
rec(true, &w);
}
pub struct A(bool);
fn rec<W>(b: bool, w: &W) {
if (b) {
rec(false, IntSt(w).0);
// rec(false, w)
}
}
fn main() {}
事实上,当考虑原始问题时,类型应该是
…MCW你在这里打乒乓球,看不到终点
- 调用
TSW::write_end(&mut self,w:&mut w)
- 哪个调用
MCW::write\u end\u all(&mut self)
- 哪个调用
TSW::write_end(&mut self,w:&mut)
- 这叫
由于不知道正确的逻辑应该是什么,我向您介绍了一个迭代解决方案:
fn write_end_all(&mut self) {
for ew in self.1.iter_mut().rev() {
ew.write_end(self.0);
// do on current el.write_end();
}
}
它更简单,不会导致尝试实例化无限多的函数,也可能根本不是您想要的功能:)我不认为您的问题与生命周期有关。rustc告诉您的是,当实例化函数
write\u end
时,它在递归过程中进入了无限循环在这里使用递归而不是迭代有什么原因吗?
- TSW<ST>::write_end<()> (&mut sel, w : &mut ())
- MCW<(), TSW<ST>>::write_end_all(&mut self)
- (f from slipt_first mut )
TSW<ST>::write_end<MCW<(),TSW<ST>>
MCW<MCW<(),TSW<ST>, > ...
fn write_end_all(&mut self) {
for ew in self.1.iter_mut().rev() {
ew.write_end(self.0);
// do on current el.write_end();
}
}