如何通过从字母数字字符中采样来创建随机字符串? [英] How do I create a random String by sampling from alphanumeric characters?
本文介绍了如何通过从字母数字字符中采样来创建随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试编译以下代码:
extern crate rand; // 0.6
use rand::Rng;
fn main() {
rand::thread_rng()
.gen_ascii_chars()
.take(10)
.collect::<String>();
}
但是cargo build
说:
warning: unused import: `rand::Rng`
--> src/main.rs:2:5
|
2 | use rand::Rng;
| ^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
error[E0599]: no method named `gen_ascii_chars` found for type `rand::prelude::ThreadRng` in the current scope
--> src/main.rs:6:10
|
6 | .gen_ascii_chars()
| ^^^^^^^^^^^^^^^
Rust编译器要求我删除use rand::Rng;
子句,同时抱怨没有gen_ascii_chars
方法.
我希望Rust只使用rand::Rng
特质,而不提供这种矛盾的错误消息.我该怎么走?
The Rust compiler asks me to remove the use rand::Rng;
clause, at the same time complaining that there is no gen_ascii_chars
method.
I would expect Rust to just use rand::Rng
trait, and to not provide such a contradictory error messages. How can I go further from here?
推荐答案
As of 0.6.0, the code should be:
extern crate rand;
use rand::Rng;
use rand::distributions::Alphanumeric;
fn main() {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.collect::<String>();
}
这篇关于如何通过从字母数字字符中采样来创建随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文