Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust - lifetime #350

Open
chochinlu opened this issue Dec 21, 2021 · 0 comments
Open

Rust - lifetime #350

chochinlu opened this issue Dec 21, 2021 · 0 comments
Labels

Comments

@chochinlu
Copy link
Owner

chochinlu commented Dec 21, 2021

https://blog.logrocket.com/understanding-lifetimes-in-rust/

lifetime不是那麼明顯要如何寫, 但是可以整理一些常見pattern

borrowing

fn f(s: &str) -> &str {
    s
} 

function的參數只有一個, 就會隱含lifetime, 這樣編譯會過

fn f(s: &str, t: &str) -> &str {
    if s.len() > 5 { s } else { t }
} 

這樣就不會過了, 需要明確給lifetime

直接都給 s 和 t 相同lifetime就可以:

fn f<'a>(s: &'a str, t: &'a str) -> &'a str {
    if s.len() > 5 { s } else { t }
} 

如果你很確定是那個lifetime, 可以指定的更加精準:

fn f<'a, 'b>(s: &'a str, _t: &'b str) -> &'a str {
    s
}

struct with reference

勁量避免在 struct使用 reference, 改用value

不過有時候也有例外, 例如你只想要做一個段落(paragraph)的頭尾sentences, 你應該不會想要拷貝所有資料, 那只要用reference並且加上 lifetime annotation就可以了:

struct S<'a> {
  first: &'a str,
  last: &'a str,
}
@chochinlu chochinlu added the rust label Dec 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant