[format_args!] cannot return value referencing function parameter

Shall be a quick question. See code below:

fn fmt<T:Debug>(msg: &T) -> Arguments {
  format_args!("{:?}", msg)

The error was:

error[E0515]: cannot return value referencing function parameter `msg`
   |   format_args!("{:?}", msg)
   |   ^^^^^^^^^^^^^^^^^^^^^---^
   |   |                    |
   |   |                    `msg` is borrowed here
   |   returns a value referencing data owned by the current function
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

However, if I inline this function into println!(), the error disappears.


// Error
println!("{}", fmt(some_debug_struct));

// Okay
println!("{}", format_args!("{:?}", some_debug_struct));

Is there a workaround?

I don't think you can use format_args! like that. Consider implementing Display for a custom type instead.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.