How is the following made to work (safely)? There are serious downsides to using 'static
.
fn whatever() {
let mut myslice = "goodbye"; //variable that lives, but not necessarily the whole program!
print!("{}", myslice);
{
let mystring = "hello".to_string();
myslice = &*mystring;
}
print!("{}", myslice);
}
The second print should produce 'hello'.
I encounter this problem commonly in lots of forms.
The open bracket could represent multiple things, like calling a function or using an if
statement.
E.g.'If there are problems with the value in myslice and things are not working properly. {'
Working out the replacement, (which proved in the above example to be 'hello') is frequently no easy or quick matter, and involves code not to be touched unless it was proved there was a problem. As is normal in Rust, there are many alternatives to &*mystring
(&mystring[..]
, : &str
on the left, &*mystring
, mystring.as_str()
, etc.) but none explicitly manipulate the perfectly available, mutable and live long enough variable as if I had typed let found = "hello".to_string; myslice = &found;' outside the curly brackets. I have tried
.clone()` in various places. Why does Rust make such a meal of this simple request? Obviously I am prepared to pay the minuscule processor time to actually do the
request.
I would like a general solution. However, it seems the above problem is explicitly with the type 'String'. e.g. let found = "hello"; let myslice = found;
seems to work, even inside the brackets. (found
is now &str
- it does not seemed ever 'borrowed'.) Is the problem directly or indirectly tied up with not knowing length at compile time? Unfortunately and frequently this is not in my control, I have to use what crates decide to give.