10

In this code from Debug examples:

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Point")
         .field("x", &self.x)
         .field("y", &self.y)
         .finish()
    }
}

let origin = Point { x: 0, y: 0 };

assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");

What does <'_> mean in f: &mut fmt::Formatter<'_>?

1

1 Answer 1

13

The ' denotes that it is a Lifetime: https://doc.rust-lang.org/rust-by-example/scope/lifetime.html

This is usually written as 'a where a is the name of the lifetime (like the name of the variable, can be any name)

The _ means that the compiler can infer the name/type. (so you don't have to figure it out, makes it easier) You can find more info here: https://stackoverflow.com/a/37215830/2037998

The <> is because of Generics. You can see that in the docs it is defines as impl<'a> Formatter<'a>

2
  • Why do we need to specify a lifetime here? And does the "guess it for me" not the default action if we specify nothing ?
    – Shengis
    Commented Dec 10, 2023 at 11:12
  • The compiler always needs to know what it is. So if it can not infer/guess it from the code around it, it will prompt you that you need to add more info. Aka you need to specify it. I'm not sure how you would create that case with Debug. But if you are using it somewhere else, avoiding lifetimes in the beginning when learning Rust is recommended. Just use variable_name.clone() usually solves it. Commented Dec 12, 2023 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.