Skip to content

Implementing fmt::Display With "{}" Causes Stack Overflow #52785

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
grippy opened this issue Jul 27, 2018 · 2 comments
Closed

Implementing fmt::Display With "{}" Causes Stack Overflow #52785

grippy opened this issue Jul 27, 2018 · 2 comments

Comments

@grippy
Copy link

grippy commented Jul 27, 2018

While implementing fmt::Display on this enum below, I accidentally used "{}" instead of "{:?}" or "{:#}".

use std::fmt;

#[derive(Debug)]
pub enum Lang {
    English
}

impl fmt::Display for Lang {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self)
    }
}

pub fn test_1() {
    println!("{}", Lang::English);    
}

fn main() {
    test_1()
}

This program bails with a fatal runtime error: stack overflow. There's no exception output provided while running w/ RUST_BACKTRACE=1 so it makes it hard to dig into the root cause.

Interestingly, if I remove the custom fmt function the compiler gives a nice explanation of what you need to do here:

error[E0277]: `Lang` doesn't implement `std::fmt::Display`
  --> src/main.rs:15:20
   |
15 |     println!("{}", Lang::English);    
   |                    ^^^^^^^^^^^^^ `Lang` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Lang`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required by `std::fmt::Display::fmt`

My issue here is that it would've been nice for the compiler to warn on the bad string binding pattern in the fmt function (similar to [E0277]).

@jonas-schievink
Copy link
Contributor

Maybe the unconditional recursion lint could catch this if it would inspect entire SCCs of the call graph (currently I think it just catches a function directly calling itself)

@estebank
Copy link
Contributor

Duplicate of #45838.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants