如何为具有生锈寿命的结构实现显示特征?

How to implement display trait for a struct with lifetime in rust?

我有一个包含字符串 (&str) 字段的结构,

struct Test<>{
    name: &str,
    city: &str,
}

在编译此结构时,它返回了生命周期错误,并且根据编译器的建议为其添加了生命周期 <'a> 有效。

use std::fmt;

#[derive(Debug)]
struct Test<'a>{
    name: &'a str,
    city: &'a str,
}

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


fn main(){
    let a = Test{name:"John",city:"London"};
    println!("{}",a);
}

然后我尝试在此结构上实现显示特征,但出现此错误。

  | impl fmt::Display for Test {
  |                       ^^^^- help: indicate the anonymous lifetime: `<'_>`

如何在 Rust 中为具有生命周期的结构实现显示特征?

简答:使用

impl<'a> fmt::Display for Test<'a>