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<'_>
?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.