【发布时间】:2021-04-05 06:34:32
【问题描述】:
问题的第一部分可能很常见,并且有足够的代码示例来解释如何生成随机的字母数字字符串。我使用的这段代码来自here。
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
fn main() {
let rand_string: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(30)
.collect();
println!("{}", rand_string);
}
但这段代码无法编译,(注意:我在夜间):
error[E0277]: a value of type `String` cannot be built from an iterator over elements of type `u8`
--> src/main.rs:8:10
|
8 | .collect();
| ^^^^^^^ value of type `String` cannot be built from `std::iter::Iterator<Item=u8>`
|
= help: the trait `FromIterator<u8>` is not implemented for `String`
好的,生成的元素是u8 类型的。所以我猜这是u8的数组或向量:
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
fn main() {
let r = thread_rng()
.sample_iter(&Alphanumeric)
.take(30)
.collect::<Vec<_>>();
let s = String::from_utf8_lossy(&r);
println!("{}", s);
}
这编译和工作!
2dCsTqoNUR1f0EzRV60IiuHlaM4TfK
一切都好,只是我想问一下是否有人可以解释关于类型的具体情况以及如何优化。
问题
-
.sample_iter(&Alphanumeric)产生u8而不是chars? - 如何避免第二个变量
s直接将u8解释为utf-8 字符?我猜内存中的表示根本不会改变? - 这些字符串的长度应始终为 30。如何优化
Vec的堆分配?他们实际上也可以是char[]而不是Strings。
【问题讨论】:
标签: string random utf-8 rust char