Sqlx query won't let me mutate the returned String

I want to replace white spaces with a "-" inside of the struct created from the returned sqlx query. I've tried iter, iter_mut, and a for for loop, but nothing I do seems to mutate it.


#[derive(FromRow, Debug, Clone)]
struct Post {
    title: String,
    post_body: String,
}

// Post is a struct with two values. Both of them String. I want to replace the white space 
// inside of my Post title with dashes "-".
let mut my_posts = sqlx::query_as::<_,Post>("select title, post_body from my_posts")
    .fetch_all(&pool)
    .await
    .unwrap();

// I want to replace spaces with dashes
for a_post in &mut my_posts {
    a_post.title.replace(" ", "-");
}

This is in an async function using tokio if that makes any difference.

this is the warning I get:

   |         a_post.title.replace(" ", "-");
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this returns the replaced string as a new allocation, without modifying the original
   = note: `#[warn(unused_must_use)]` on by default

You need to assign the new String to the title field

for a_post in &mut posts {
    a_post.title = a_post.title.replace(" ", "-");
}
1 Like

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.