How to convert sub Vec<char> to a sub-string

I want slice something as a sub-string from chars, I can implement it use fn slice {...} below, but I don't think my implementation is good. Is there some better way to do that?

#![allow(unused)]
fn main() {
    let chars = vec!['h', 'e', 'l', 'l', 'o'];
    
    let hello = slice(&chars, 0, 5);
    assert_eq!(String::from("hello"), hello);
}

fn slice(chars: &Vec<char>, start: usize, end: usize) -> String {
    let mut s = String::from("");
    for i in start..end {
        s.push_str(chars.get(i).unwrap().to_string().as_str());
    }
    
    s
}

(Playground)

Use collect. Example:

chars[start..end].iter().copied().collect()

Playground

Edit: Apparently you don't even need .copied(). And

chars[start..end].iter().collect()

is enough.

5 Likes

You should take &[char] as an argument, not &Vec<char>.

I also suggest calling the function something besides slice, as in normal Rust nomenclature taking a (sub-)slice implies some sort of cheap borrow, not the allocation of a new structure.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.