These are chat archives for rust-lang/rust

22nd
May 2018
Farhan Ahmed
@IMacronaut_twitter
May 22 2018 10:32 UTC
What is the best way to generate random numeric strings of fixed size? ‘4356722' for trivial things.
apiraino
@apiraino
May 22 2018 10:39 UTC
@IMacronaut_twitter a random generator? Have a look at a password generator, it may give you some ideas
Dmitriy
@dpogretskiy
May 22 2018 10:50 UTC
@IMacronaut_twitter in case you don't care about anything realy, this works
extern crate rand;

fn main() {
    let random_password = std::iter::repeat::<usize>(0)
        .map(|_| rand::random::<char>())
        .filter(|a| a.is_ascii_alphanumeric())
        .take(50)
        .collect::<String>();
    println!("{:?}", random_password);
}
Michal 'vorner' Vaner
@vorner
May 22 2018 11:04 UTC
Also, you can replace the repeat(0).map(|_| …) with this: https://docs.rs/itertools/0.7.8/itertools/fn.repeat_call.html
apiraino
@apiraino
May 22 2018 11:09 UTC
and .filter(|a| a.is_digit(10)) if you only need to generate a string with numbers
Restioson
@Restioson
May 22 2018 13:19 UTC
Probably a better way to do it is to ask rand to give you values in range of ascii
Dmitriy
@dpogretskiy
May 22 2018 13:19 UTC
@Restioson it's only applicable when you care :laughing:
Restioson
@Restioson
May 22 2018 14:20 UTC
I guess lol
Dmitriy
@dpogretskiy
May 22 2018 14:24 UTC
in that case you just do good known math of kind (random % (ascii_max - ascii_min)) + ascii_max) as char
then you will probably draw a distinction between digits and letters, maybe capital letters too, or you can try to do it for non ascii languages like german, whole lot of fun.
Farhan Ahmed
@IMacronaut_twitter
May 22 2018 17:58 UTC
@apiraino and @dpogretskiy Thank you. I will give your suggestions a shot.
I’m trying to find my way around Rust and coming from OOP background, I have to wrap my head around simple paradims and concepts.
Farhan Ahmed
@IMacronaut_twitter
May 22 2018 18:32 UTC
So about traits. How do I go about using composition with traits? Is this possible:
trait SaveCycle
{
    fn did_save(&self) -> bool;
}

trait DeleteCycle
{
    fn did_delete(&self) -> bool;
}

trait SaveDeleteCycle: SaveCycle + DeleteCycle
{
    ...
}
Or something similar to it.
Andrey Lesnikov
@ozkriff
May 22 2018 18:35 UTC
yep http://play.rust-lang.org/?gist=92ba6cb5c0262c8f6ae4210fc6c677ee it works exactly like you've written
Farhan Ahmed
@IMacronaut_twitter
May 22 2018 18:41 UTC
@ozkriff Hm. Even though a struct has the C trait, it still needs to provide the A and B implementation separately. Am I reading that correctly?
Andrey Lesnikov
@ozkriff
May 22 2018 18:42 UTC
yep, C depends on A and B
Farhan Ahmed
@IMacronaut_twitter
May 22 2018 18:42 UTC
I was hoping to reduce the bioler plate and have the struct implement C for it, and hoping the methods fromA and B would flow into the struct’s impl for C.
I guess I need to spend a bit more time with Traits.
Thank you @ozkriff