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
}
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.