Skip to content

Instantly share code, notes, and snippets.

@taikulawo
Last active December 8, 2020 15:48
Show Gist options
  • Save taikulawo/b40b184b1d61abaa5cedbf8f4b0e77b6 to your computer and use it in GitHub Desktop.
Save taikulawo/b40b184b1d61abaa5cedbf8f4b0e77b6 to your computer and use it in GitHub Desktop.

下面两端都能编译通过 刚才又理解了下,&str有可能引用了 slice,但编译器单从 struct 上并不能区分是 字符串常量还是 slice,所以需要显式声明周期标识 当然,如果确实是 字符串常量编译器允许你使用 'static 标识(活得永远比当前struct长)

// 自问自答下,纵使为static生命周期也必须要进行标注便于编译器进行推导
struct Person {
    name: &'static str,
}

impl Person {
    fn new(name: &'static str) -> Person {
        Person { name: name }
    }
}
fn main() {
    let nobody: Person = Person::new("nobody");
}
struct Person<'a> {
    name: &'a str,
}
// Person已经标注a周期,这里可以显式省略掉
impl Person<'_> {
    fn new(name: &str) -> Person {
        Person { name: name }
    }
}
fn main() {
    let nobody: Person = Person::new("nobody");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment