How do I transform &str to ~str in Rust?

pointers, rust, rust-obsolete, string

Solution

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

Problem

This is for the current 0.6 Rust trunk by the way, not sure the exact commit. Let's say I want to for each over some strings, and my closure takes a borrowed string pointer argument (&str). I want my closure to add its argument to an owned vector of owned strings ~[~str] to be returned. My understanding of Rust is weak, but I think that strings are a special case where you can't dereference them with * right? How do I get my strings from &str into the vector's push method which takes a ~str? Here's some code that doesn't compile ``` 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); } result } ``` It doesn't compile because it's inferring result's type to be [&str] since that's what I'm pushing onto it. Not to mention its lifetime will be wrong since I'm adding a shorter-lived variable to it. I realize I could use ReaderUtil's read_line() method which returns a ~str. But this is just an example. So, how do I get an owned string from a borrowed string? Or am I totally misunderstanding.

Original source