简体   繁体   中英

How can I convert a String into a Vector in Rust?

I was wondering how to convert a styled string into a vector. Say I had a String with the value:

"[x, y]"

-how could I turn it into a vector that has x as the first object and y as the second object?

Thanks!

Sure, but the elements can't be references. As mentioned by @prog-fh that isn't possible in rust since once compiled, variable names may not be stored and the compiler may have even removed some during optimizations.

You can however do something more similar to python's ast.literal_eval using serde with Rust Object Notation (RON, a type of serialization that was made to resemble rust data structures). It isn't perfect, but it is an option. It does however require you know what types you are trying to parse.

use ron::from_str;

let input = "[37.6, 24.3, 89.023]";
let parsed: Vec<f32> = from_str(input).unwrap();

On the other hand if @mcarton is correct and you want something like vec!["x", "y"] , you could manually parse it like so:

fn parse(input: &str) -> Option<Vec<String>> {
    let mut part = String::new();
    let mut collected = Vec::new();

    let mut char_iter = input.chars();

    if char_iter.next() != Some('[') {
        return None
    }

    loop {
        match char_iter.next()? {
            ']' => {
                collected.push(part);
                return Some(collected)
            }
            ',' | ' ' => {
                if !part.is_empty() {
                    collected.push(part);
                    part = String::new();
                }
            }
            x => part.push(x),
        }
    }
}

println!("{:?}", parse("[a, b, foo]"));

Or you could also use a regex to break it up instead, but you can look into how that works yourself.

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