How do I transform &str to ~str in Rust?
You should call the StrSlice trait's method, to_owned, as in:
fn read_all_lines() -> ~[~str] {
let mut result = ~[];
let reader = io::stdin();
let util = @reader as @io::ReaderUtil;
for util.each_line |line| {
result.push(line.to_owned());
}
result
}
StrSlice trait docs are here:
http://static.rust-lang.org/doc/core/str.html#trait-strslice
You can't.
For one, it doesn't work semantically: a ~str
promises that only one thing owns it at a time. But a &str
is borrowed, so what happens to the place you borrowed from? It has no way of knowing that you're trying to steal away its only reference, and it would be pretty rude to trash the caller's data out from under it besides.
For another, it doesn't work logically: ~
-pointers and @
-pointers are allocated in completely different heaps, and a &
doesn't know which heap, so it can't be converted to ~
and still guarantee that the underlying data lives in the right place.
So you can either use read_line
or make a copy, which I'm... not quite sure how to do :)
I do wonder why the API is like this, when &
is the most restricted of the pointers. ~
should work just as well here; it's not like the iterated strings already exist somewhere else and need to be borrowed.