#Error compiling tests but not when running `cargo check --tests`

4 messages · Page 1 of 1 (latest)

quick remnant
#

I have the following (minimized) code:

use std::fmt::{self, Write};

#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct RenderMe {
    content: String,
    next: Option<Vec<RenderMe>>
}

pub fn render<W: Write>(mut writer: W, to_render: RenderMe) -> Result<(), fmt::Error> {
    writer.write_str(&to_render.content)?;
    if let Some(next) = to_render.next {
        for item in next {
            render(&mut writer, item)?;
        }
    }
    Ok(())
}

pub fn render_to_string(to_render: RenderMe) -> Result<String, fmt::Error> {
    let mut result = String::new();
    render(&mut result, to_render)?;
    Ok(result)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_render_to_string() {
        assert_eq!(Ok("".to_owned()), render_to_string(RenderMe::default()))
    }
}

When run cargo check --tests everything is fine but if I try to actually run the tests (cargo test) I get the following compile time error:

   Compiling test_rs v0.1.0 (redacted)
error: reached the recursion limit while instantiating `render::<&mut &mut &mut &mut &mut ...>`
  --> src/lib.rs:13:13
   |
13 |             render(&mut writer, item)?;
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: `render` defined here
  --> src/lib.rs:9:1
   |
9  | pub fn render<W: Write>(mut writer: W, to_render: RenderMe) -> Result<(), fmt::Error> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: the full type name has been written to 'redacted'
#
error: could not compile `test_rs` due to previous error
warning: build failed, waiting for other jobs to finish...
error: reached the recursion limit while instantiating `render::<&mut &mut &mut &mut &mut ...>`
  --> src/lib.rs:13:13
   |
13 |             render(&mut writer, item)?;
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: `render` defined here
  --> src/lib.rs:9:1
   |
9  | pub fn render<W: Write>(mut writer: W, to_render: RenderMe) -> Result<(), fmt::Error> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: the full type name has been written to 'redacted'

error: could not compile `test_rs` due to previous error

I am trying to write to the same String in a loop and in various functions. Since I need to write to the same String in each, I give the next render_something function a mutable reference to the Writer instead, since I want to continue writing to the same Writer in the next loop iteration.

#

For context: The actual data structure is an AST I parsed earlier and the function is "interpreting" the AST and rendering the output.

pulsar marten
#

You could make render take &mut W, and then call it with just writer. Normally that's bad but it should fix this problem. Or have it return Result<W, _> and reassign writer with the output.

Or do it iteratively.