Skip to content

Instantly share code, notes, and snippets.

@joladev
Last active December 26, 2015 03:09
Show Gist options
  • Save joladev/7084285 to your computer and use it in GitHub Desktop.
Save joladev/7084285 to your computer and use it in GitHub Desktop.
Attempt at random string generation in Rust
use std::rand;
use std::rand::Rng;
use std::str;
static TARGET: &'static str = "methinks it is like a weasel";
static ALPHABET: &'static [u8] = bytes!("abcdefghijklmnopqrstuvwxyz");
fn random_char() -> u8 {
rand::task_rng().choose(ALPHABET)
}
fn random_string () -> ~str {
let mut result = str::with_capacity(TARGET.len());
for _ in range(0, TARGET.len()) {
result.push_char(random_char() as char);
}
result
}
fn main() {
println(random_string());
}
@nixpulvis
Copy link

Something I came up with in Rust 0.11

fn random_string(length: uint) -> String {
  let mut string = String::new();
  for char in rand::task_rng().gen_ascii_chars().take(length) {
    string.push_char(n);
  }
  string
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment