Search code examples
rustrust-cargo

How to remove quotes from the value of a variable in rust


I need to remove the quotes from the value of the variable, so that a variable of a different type is obtained. From this:

let mut first_variable = "[67, 43, 26, 72]";

Into this:

let mut second_variable = [67, 43, 26, 72];

This should be executed while the program is running.


Solution

  • You can use the serde-json crate:

    use serde_json; // 1.0.82
    
    let k:[u32; 4] = serde_json::from_str("[67, 43, 26, 72]").unwrap();
    

    Or if you want it to work regardless of length:

    let k:Vec<u32> = serde_json::from_str("[67, 43, 26, 72]").unwrap();
    

    Of course replace u32 with whatever numeric type you actually want.