I get different results on puzzle 15

Rust Brain Teasers: description (Puzzle15: To Infinity)

On this line:

  fn fmt(&self, f: &mut fmt::Formatter<`_>) -> fmt::Result {

Formatter<`_> is flagged as an error (“this struct takes 0 generic arguments but 1 generic argument was supplied”).

When I “correct” it to f: &mut fmt::Formatter then the program runs just fine) only spits out one line and exits normally. It does not spit out node after node until it gets a stack overflow.

I do get a “dead code” warning on the prev property of Node, so maybe that’s being optimized out, thus avoiding your error?

Full source for reference:

use std::cell::RefCell;
use std::rc::Rc;

type Link = Option<Rc<RefCell<Node>>>;

// #[derive(Debug)]
struct Node {
    elem: i32,
    next: Link,
    prev: Link,
}

impl Node {}

use std::fmt;
impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "elem: {}", self.elem)
    }
}

fn main() {
    let mut head = Some(Rc::new(RefCell::new(Node {
        elem: 1,
        next: None,
        prev: None,
    })));
    head.as_mut().unwrap().borrow_mut().next = Some(Rc::new(RefCell::new(Node {
        elem: 2,
        next: None,
        prev: head.clone(),
    })));
    println!("{:?}", head);
}

also for reference:

rustup show
Default host: x86_64-apple-darwin
rustup home:  /Users/mike/.rustup

installed toolchains
--------------------

stable-x86_64-apple-darwin (default)
nightly-x86_64-apple-darwin

installed targets for active toolchain
--------------------------------------

wasm32-unknown-unknown
x86_64-apple-darwin

active toolchain
----------------

stable-x86_64-apple-darwin (default)
rustc 1.55.0 (c8dfcfe04 2021-09-06)