You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The get and get_mut methods of Value accept any type that implements Index, as does the square-bracket indexing operator. This trait is implemented for strings which are used as the index into a JSON map, and for usize which is used as the index into a JSON array.
So using the squar-bracket operator with any other combination of index type and Value variant isn't well-defined. The exact implementation seems a bit nuanced. Here's my assessment of what's going on:
You have a mutable Value::String
You try to access ["some_key"]. Regardless of what the semantics of that are, Rust's type system requires that to return a mutable reference to a Value (i.e., &mut Value).
Now since that key doesn't exist the best thing serde_json could give you is a Value::Null. But where to get a mutable reference to one from? If the Value on which you do the lookup is a map, serde_json will insert a Null under that key and then give you back a mutable reference. Easy. But there's nothing that can be done about that if the Value is a String.
Options forward:
Don't make the value mutable. In that case, serde_json will hand you a reference to a static Null Value if the key doesn't exist or you try to look something up in a Value variant that doesn't support that index type.
Alternatively, you can use Value::get to make sure you don't request a mutable reference. In that case, serde_json will hand you None if the lookup fails.
I have a code like this
First
println!
Shows that taking from missing key returns Value::Null variant. And this is what we all expect from
Value::take(&mut self)
.Second
take()
panicsAnd second
println!
is never reached.My toolchain is
stable-x86_64-unknown-linux-gnu - rustc 1.84.0 (9fc6b4312 2025-01-07)
.The text was updated successfully, but these errors were encountered: