Dragomir
Dragomir

Reputation: 43

How to convert Rc<str> to String in Rust

I am currently trying to build an interpreter in Rust in order to better understand it(both interpreters and Rust). I converted input string into Rc<str> and in later stage of compilation I want to create a String from part of it. I couldn't find anything that can help me in documentation so I wrote a simple function that looks like this`

fn string_from_rc(r: &std::rc::Rc<str>) -> String {
    let chars = r.chars();
    let mut s = String::new();
    for c in chars {
        s.push(c);
    }
    s
}

but I am sure there is a better way to go about this problem.

Upvotes: 2

Views: 1067

Answers (1)

ramsl&#246;k
ramsl&#246;k

Reputation: 145

.to_string() is enough:

fn string_from_rc(r: &std::rc::Rc<str>) -> String {
    r.to_string()
}

Equivalent would also be a .to_owned() called on the str value. One simple thing to remember is that if you have a &Rc<str>, then all the methods of &str are still available, but maybe in some cases the trait methods of the smart pointer type (here Rc) get in the way.

.to_string() comes from the ToString trait, which str of course implements.

Upvotes: 2

Related Questions