Mutate value within Result<T,E> before returning

I have a function that returns Result<T, E>, that I get from parsing some JSON string using serde.
Before returning this value, I want to perform some mutations to T. What is the idiomatic way of doing so?

Right now, I am doing something like this:

fun foo() -> Result<T,E> {
    let bar: Result<T,E> = serde_json::from_str(...);
    let bar = if let Ok(mut val) = bar {
        val.some_mutating_operation();
        Ok(val)
    }else{
       bar
    }
    
    bar
}

but this does not seem elegant to me.

let mut val = serde_json::from_str("...")?;
val.some_mutating_operation();
Ok(val)
1 Like

Thanks @Hyeonu. That works for me!

Sounds like a case for the map method, or am I missing something?

2 Likes

map would work if some_mutating_operation was of a kind (self) -> Self, but here it's more like (&mut self) -> ().