gpt4 book ai didi

rust - 如何将 i32 数字的 Vec<> 加入字符串?

转载 作者:行者123 更新时间:2023-12-03 11:32:18 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What's an idiomatic way to print an iterator separated by spaces in Rust?

(4 个回答)


去年关闭。




我想将一个数字列表加入一个字符串。我有以下代码:

let ids: Vec<i32> = Vec::new();
ids.push(1);
ids.push(2);
ids.push(3);
ids.push(4);
let joined = ids.join(",");
print!("{}", joined);

但是,我收到以下编译错误:
error[E0599]: no method named `join` found for struct `std::vec::Vec<i32>` in the current scope
--> src\data\words.rs:95:22
|
95 | let joined = ids.join(",");
| ^^^^ method not found in `std::vec::Vec<i32>`
|
= note: the method `join` exists but the following trait bounds were not satisfied:
`<[i32] as std::slice::Join<_>>::Output = _`

我有点不清楚该怎么做。我了解特征的实现,但无论它期望什么特征,我都希望为 i32 本地实现.我希望将整数加入一个字符串比这更简单。我是否应该将它们全部转换为 String首先?

编辑 : 和 the linked question不一样因为这是专门询问数字不能直接“ join能够”,以及数字类型不能实现特征的原因。我相当努力地寻找这个方向的东西,但一无所获,这就是我问这个问题的原因。

最佳答案

如果您不想显式转换为字符串,则可以使用 Itertools::join trait 方法(虽然这是一个外部 crate )。

use itertools::Itertools;

let mut ids: Vec<i32> = ...;
let joined = ids.iter().join(".");
print!("{}", joined);

( Playground )

关于rust - 如何将 i32 数字的 Vec<> 加入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032075/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com