Skip to content

Instantly share code, notes, and snippets.

@joladev
Last active December 24, 2015 13:39
Show Gist options
  • Save joladev/6807138 to your computer and use it in GitHub Desktop.
Save joladev/6807138 to your computer and use it in GitHub Desktop.
Random string generation in Rust (for Weasel)
use std::rand;
use std::rand::Rng;
use std::str;
static TARGET: &'static str = "methinks it is like a weasel";
static ALPHABET: [char, ..26] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
fn random_char() -> char {
rand::rng().choose(ALPHABET)
}
fn builder(push: &fn(v: char)) {
for _ in range(0,TARGET.len()) {
push(random_char());
}
}
fn random_string () -> ~str {
let result = std::vec::build(Some(TARGET.len()), builder);
str::from_chars(result)
}
fn main() {
println(random_string());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment