Snafu: How to access struct fields in a format string?

Learning Snafu:

#[derive(Debug, Snafu)]                                                                          
enum Error {                                                                   
    #[snafu(display("{at:?}: {}", num))]                                                         
    Fuba {                                                                                       
        num: u64,                                                                                
        #[snafu(implicit)]                                                                       
        at: Location,                                                                            
    },                                                                                           
} 
                                                                                                                                                                                             
fn fuba(arg: u64) -> Result<u64, Error> {                                                        
    ensure!(arg >= 5, FubaSnafu { num: arg });                                                   
    Ok(arg)                                                                                      
}
// ...

This works and yields:

Location { file: "threads/src/bin/snafu.rs", line: 16, column: 5 }: 1

This is what I wanted.

But how do I access the other fields in Location?

I can't find a way to access Location fields in the format string.
You should be able to format Location fields just like you're doing with num: use {} in the format string and pass at.line (for example) as a parameter.

But note that there are no other public fields, just those three.

1 Like

Thanks, i tried this already but it doesn’t work “directly”. at.line isn’t expanded in a format string. By chance i found:

#[snafu(display("{file:?} {line:?} {column:?} {num}",                                        
                    file = at.file, line = at.line, column = at.column))]

Which yields "threads/src/bin/snafu.rs" 17 5 1

Nothing is easy - especially in Rust.

I edited but you may have missed it, sorry. I suggested passing at.line as a parameter, as one would do normally in println, assert, etc, and as you had done with num.

#[snafu(display("{} {} {} {}", at.file, at.line, at.column, num))]

But I'm glad you found a solution.

1 Like

D'oh! Yes, sure. My "solution" is somewhat cumbersome [1]. Thanks again.


  1. And maybe I still haven't learned enough English. ↩︎

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.