flâneur

Creating a Rust function that returns a &str or String

hermanradtke.com · 1,473 words · saved by 1 readers

We learned how to create a function that accepts String or &str as an argument. Now I want to show you how to create a function that returns either String or &str. I also want to discuss why we would want to do this. To start, let us write a function to remove all the spaces from a given string. Our function might look something like this:

Russian Translation We learned how to create a function that accepts String or &str as an argument. Now I want to show you how to create a function that returns either String or &str. I also want to discuss why we would want to do this. To start, let us write a function to remove all the spaces from a given string. Our function might look something like this: fn remove_spaces(input: &str) -> String { let mut buf = String::with_capacity(input.len()); for c in input.chars() { if c != ' ' { buf.push(c); } } buf } This function allocates memory for a string buffer, loops through each…

related reading