This is valid D language code:
void main() {
import std.conv: to;
auto a1 = "[1, 2, 3]".to!(uint[3]);
auto a2 = "[1, 2, 3]".to!(uint[]);
}
It shows that the standard “to” parsing function allows to convert a string to both a in-place stack-allocated fixed-size array and a heap-allocated dynamic array (it raises an exception if there’s a parsing error or lengths don’t match).
In Haskell you can do about the same (to a list):
a2 :: [Int]
a2 = read "[1, 2, 3]"
Currently to do the same in Rust you need more complex code (you could write it in some other ways):
fn main() {
let mut a1 = [0u32; 3];
let mut last = None;
for (i, n) in "[1, 2, 3]"
.trim_matches(|c| c == '[' || c == ']')
.split(',')
.enumerate() {
last = Some(i);
a1[i] = n.trim().parse::<u32>().unwrap();
}
assert_eq!(last, Some(a1.len() - 1));
let a2: Vec<u32> =
"[1, 2, 3]"
.trim_matches(|c| c == '[' || c == ']')
.split(',')
.map(|n| n.trim().parse().unwrap())
.collect();
}
I’d like something similar in Rust std:
fn main() {
let a1: [u32; 3] = "[1, 2, 3]".parse().unwrap();
let a2: Vec<u32> = "[1, 2, 3]".parse().unwrap();
}