'Shadow variable not working in Rust, gives lifetime errors
Here is my snippet:
pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
phrase = phrase.replace("-", "");
}
Gives this error
1 | pub fn abbreviate(mut phrase: &str) -> String {
| ---- expected due to this parameter type
...
4 | phrase = phrase.replace("-", "");
| ^^^^^^^^^^^^^^^^^^^^^^^
| |
| expected `&str`, found struct `String`
| help: consider borrowing here: `&phrase.replace("-", "")`
if I follow the suggestion
pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
phrase = &phrase.replace("-", "");
}
I get this lifetime compile error
1 | pub fn abbreviate(mut phrase: &str) -> String {
| - let's call the lifetime of this reference `'1`
...
4 | phrase = &phrase.replace("-", "");
| ----------^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'1`
This works but is ugly:
pub fn abbreviate(mut phrase: &str) -> String {
let mut tla = String::new();
let phrase2 = &phrase.replace("-", "");
}
Why can I not shawdow the phrase variable? Can somebody please explain the above compiler error about lifetimes?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
