我该如何将一个
例如,
我想这样做的原因是我想使用来自TUI的条形图绘制我的向量,而这需要像那样的类型。
我尝试了一些显然的方法,如循环和推送:
Vec<u64>
转换成Vec<(&str, u64)>
,使得前者的索引嵌入到后者的str
部分中?例如,
[4,9,3]
应该被转换为[("0", 4), ("1", 9), ("2", 3)]
。我想这样做的原因是我想使用来自TUI的条形图绘制我的向量,而这需要像那样的类型。
我尝试了一些显然的方法,如循环和推送:
fn main() {
let my_vec: Vec<u64> = vec![4, 9, 3];
let mut result: Vec<(&str, u64)> = Vec::new();
for (k, v) in my_vec.iter().enumerate() {
result.push((&k.to_string(), *v));
}
assert_eq!(result, [("0", 4), ("1", 9), ("2", 3)]);
}
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:5:23
|
5 | result.push((&k.to_string(), *v));
| ^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
...
8 | assert_eq!(result, [("0", 4), ("1", 9), ("2", 3)]);
| --------------------------------------------------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
或者使用map
:
fn main() {
let my_vec: Vec<u64> = vec![4, 9, 3];
let result: Vec<(&str, u64)> = my_vec
.into_iter()
.enumerate()
.map(|(k, v)| (&k.to_string(), v))
.collect();
assert_eq!(result, [("0", 4), ("1", 9), ("2", 3)]);
}
error[E0277]: a value of type `std::vec::Vec<(&str, u64)>` cannot be built from an iterator over elements of type `(&std::string::String, u64)`
--> src/main.rs:7:10
|
7 | .collect();
| ^^^^^^^ value of type `std::vec::Vec<(&str, u64)>` cannot be built from `std::iter::Iterator<Item=(&std::string::String, u64)>`
|
= help: the trait `std::iter::FromIterator<(&std::string::String, u64)>` is not implemented for `std::vec::Vec<(&str, u64)>`
但是无论我做什么,都似乎无法解决生命周期问题,因为k.to_string()
的生命周期不够长。
当然,如果有更好的方法可以用向量的索引作为标签绘制图形,我很乐意听取建议。