[英]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]" “[x,y]”
-how could I turn it into a vector that has x as the first object and y as the second object? -我怎么能把它变成一个向量,其中 x 作为第一个对象,y 作为第二个对象?
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.正如@prog-fh 所提到的,自从编译后,在 rust 中是不可能的,变量名可能不会被存储,编译器甚至可能在优化过程中删除了一些。
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).但是,您可以使用带有Rust 对象表示法(RON,一种类似于Rust数据结构的序列化类型)的ast.literal_eval
来执行更类似于 python 的ast.literal_eval
操作。 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:另一方面,如果@mcarton 是正确的,并且你想要像vec!["x", "y"]
,你可以像这样手动解析它:
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.或者您也可以使用正则表达式来分解它,但您可以自己研究它是如何工作的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.