简体   繁体   中英

How to modify a string inside a serde_json::Value::String?

I have a serde_json::Value containing a string that I want to modify, if possible without cloning the string. I would imagine you would do it like this:

let mut value = Value::String("Hello world".to_string());
let mut string = value.as_mut_string().unwrap();
string.push('!');

But there is no such thing as as_mut_string . I could do this:

let mut value = Value::String("Hello world".to_string());
let mut string = value.as_str().unwrap().to_string();
string.push('!');
value = Value::String(string);

However, this is both ugly code and inefficient since I have to clone the string. Is there a better solution?

serde_json::value::Value is an enum , you can just pattern match it:

let mut value = Value::String("Hello world".to_string());
if let Value::String(string) = &mut value {
    string.push('!');
}

println!("{:?}", value);

( Permalink to the playground )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM