Minimal setup to swap first two chars in the input &str and return a String where the function signature is fixed
⚓ Rust 📅 2026-02-20 👤 surdeus 👁️ 5Hi all,
I have been trying to solve an exercism exercise using Rust. The function signature is fixed and I can't change it. The real task is more complex but knowing how to fix the code below will give me insight to solve my issue over at exercism.
I posted the below code to show my intention instead of the entire history of what I tried. I would appreciate it if someone can show me the most idiomatic way to return the text in the_string_to_modify with the first two characters swapped within the constraints of the modify_string function signature.
fn modify_string(the_string_to_modify: &str) -> String
{
//I tried this but still cryptic error messages
//let mut working_the_string_to_modify_copy = the_string_to_modify.clone();
let mut aux = b'0';
//Replaced the_string_to_modify with working_the_string_to_modify_copy
//but not success in what I have tried
aux = the_string_to_modify.as_bytes()[0];
the_string_to_modify.as_bytes()[0] = the_string_to_modify.as_bytes()[1];
the_string_to_modify.as_bytes()[1] = aux;
the_string_to_modify.to_string()
}
fn main()
{
let string_to_modify = "abc";
let modified_string = modify_string(string_to_modify);
println!("{modified_string}");
}
3 posts - 3 participants
🏷️ Rust_feed