We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
https://blog.logrocket.com/understanding-lifetimes-in-rust/
lifetime不是那麼明顯要如何寫, 但是可以整理一些常見pattern
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使用 reference, 改用value
不過有時候也有例外, 例如你只想要做一個段落(paragraph)的頭尾sentences, 你應該不會想要拷貝所有資料, 那只要用reference並且加上 lifetime annotation就可以了:
struct S<'a> { first: &'a str, last: &'a str, }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
https://blog.logrocket.com/understanding-lifetimes-in-rust/
lifetime不是那麼明顯要如何寫, 但是可以整理一些常見pattern
borrowing
function的參數只有一個, 就會隱含lifetime, 這樣編譯會過
這樣就不會過了, 需要明確給lifetime
直接都給 s 和 t 相同lifetime就可以:
如果你很確定是那個lifetime, 可以指定的更加精準:
struct with reference
勁量避免在 struct使用 reference, 改用value
不過有時候也有例外, 例如你只想要做一個段落(paragraph)的頭尾sentences, 你應該不會想要拷貝所有資料, 那只要用reference並且加上 lifetime annotation就可以了:
The text was updated successfully, but these errors were encountered: