Creating a Rust function that returns a &str or String
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
- Working with strings in Rustfasterthanli.me
- What is Ownership? - The Rust Programming Languagedoc.rust-lang.org
- The Slice Type - The Rust Programming Languagedoc.rust-lang.org
- A half-hour to learn Rustfasterthanli.me
- References and Borrowing - The Rust Programming Languagedoc.rust-lang.org
- Rust Language Cheat Sheetcheats.rs
- Storing UTF-8 Encoded Text with Strings - The Rust Programming Languagedoc.rust-lang.org
- Moves, cloning, and copying - Rust for C-Programmersrust-for-c-programmers.com
- Summary - Rust for C-Programmersrust-for-c-programmers.com
- Rewriting Bun in Rust | Bun Blogbun.com
- Fast and Simple Rust Internermatklad.github.io
- Moves - Rust: A Better C++ Than C++thecodedmessage.com