怎么解决这个问题呢?

#[derive(Debug, Clone)]
struct Person {
    pub name: &'static str,
    pub age: u32,
    pub email: Option<String>,
}
static INIT: Once = Once::new();

impl Person {
    fn new(name: &str, age: u32) -> Self {
        Self {
            name: name,
            age: age,
            email: None,
        }
    }
}
#[test]
fn test001() {
    let name = String::from("test001");
    test002(name.as_str());
}
fn test002(name: &str) -> Person {
    test003(name)
}
fn test003(name: &str) -> Person {
    let person = Person::new(name, 32);
    return person;
}

编译异常

error: lifetime may not live long enough
  --> src/test/test_aaa.rs:17:19
   |
15 |     fn new(name: &str, age: u32) -> Self {
   |                  - let's call the lifetime of this reference `'1`
16 |         Self {
17 |             name: name,
   |                   ^^^^ this usage requires that `'1` must outlive `'static`

方案一:将字段类型改为 String
将 name 字段的类型从 &'static str 改为 String,这样可以拥有字符串数据,避免生命周期问题。

#[derive(Debug, Clone)]
struct Person {
    pub name: String,
    pub age: u32,
    pub email: Option<String>,
}

方案二:使用 Box<str> 作为 name 字段
如果你希望保持 name 字段为引用类型,但仍然避免生命周期问题,可以使用 Box<str>。这允许你存储堆分配的字符串切片。

#[derive(Debug, Clone)]
struct Person {
    pub name: Box<str>,
    pub age: u32,
    pub email: Option<String>,
}

方案三:使用 Cow<str>
Cow(Clone on Write)是一种智能指针,可以在需要时进行克隆。它可以在需要时将借用的字符串转换为拥有的字符串,从而避免生命周期问题。

#[derive(Debug, Clone)]
struct Person {
    pub name: Cow<'static, str>,
    pub age: u32,
    pub email: Option<String>,
}

impl Person {
    fn new(name: &str, age: u32) -> Self {
        Self {
            name: Cow::Owned(name.to_string()),
            age,
            email: None,
        }
    }
}

putao
8 声望1 粉丝

推动世界向前发展,改善民生。