rust - 将向量解析为正确的类型

标签 rust

有没有一种方法可以将String动态转换为其他类型?我有一个格式为key:type:value的值向量,我想将其转换为键值对,其中值已转换为正确的类型。在这种情况下,类型映射为:i=i64f=f64

到目前为止,我有这个:

fn main() {
    let arr: Vec<String> = vec!["A:i:49".to_string(), "B:f:0.1374".to_string()];

    let tup: Vec<_> = arr
        .iter()
        .map(|s| s.split(":").collect::<Vec<&str>>())
        .collect();

    println!("Arr: {:#?}", arr);
    println!("Tup: {:?}", tup)
}

// Arr: [
//     "A:i:49",
//     "B:f:0.1374",
// ]
// Tup: [["A", "i", "49"], ["B", "f", "0.1374"]]

希望达到以下效果:
[("A", 49), ("B", 0.1374)]

我已经看过泛型/实现,但无法解决该怎么做。

注意:任何vec都可以具有任何键,因此下一个集合可以是["A:i:99", "C:i:0"],类型限于整数,浮点数和字符串。

最佳答案

使用Enum包装器类型的解决方案

#[derive(Debug)]
enum Value {
    IntVal(i32),
    FloatVal(f64),
}


let tup: Vec<_> = arr
    .iter()
    .map(|s| {
        let mut values = s.split(":");
        let first_tk = values.next().unwrap();
        let second_tk = values.next().unwrap();
        let third_tk = values.next().unwrap();
        let value = match second_tk {
            "i" => Value::IntVal(FromStr::from_str(third_tk).expect("Invalid int")),
            "f" => Value::FloatVal(FromStr::from_str(third_tk).expect("invalid float")),
            _ => panic!("unexpected pattern {}", second_tk),
        };
        (first_tk, value)
    })
    .collect();

游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0e8ae249e91cb0055f09c9b1bd96ebde

Note: You need to do proper error handling and current code just panics whenever it encounters unexpected value. You need to use Result type for that. Also, you could explore FromStr trait to parse from string

关于rust - 将向量解析为正确的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62105497/

相关文章:

c - Read raw C string to Rust...在此上下文中将有符号转换为无符号的正确方法是什么?

rust - 创建内联静态值的方法

rust - 如何使用构建器模式生成的数据

asynchronous - 如何在 Rust 中返回一个返回特征的函数

fold - Rust 中的折叠问题

rust - 加入 &str 的迭代器

rust - 如何确定由 include! 包含的 rust-protobuf 生成的 .rs 文件中的消息宏观

rust - 如何在 Tokio 中安排重复任务?

rust - 为什么 Rust 中的 WASM 库必须将 crate-type 设置为 cdylib?

ubuntu - 使用 prefer-dynamic 时无法执行 hello world 项目