mardi 18 mai 2021

Array unexpectedly not modified by function

The code runs just fine but all values are 0, when they should be numbers randomly generated from a range of 0 and 60 / 300, as in the code. Using Rust playground as ide.

#![allow(dead_code, mutable_transmutes, non_camel_case_types, non_snake_case,
         non_upper_case_globals, unused_assignments, unused_mut)]
const MAX: usize = 16;
#[derive(Copy, Clone)]
struct time {
    h: i32,
    m: i32,
    s: i32,
}

fn rnd (mut x: [time; MAX], y: usize) {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let mut i: usize = 0;
    while i < y {
        x[i].h = rng.gen_range(0..300);
        x[i].m = rng.gen_range(0..60);
        x[i].s = rng.gen_range(0..60);
        i+=1;
    }
}

fn main () {
    let mut a: [time; MAX] = [time{h: 0, m: 0, s: 0,}; MAX];
    let mut i: usize = 0;
    rnd(a, MAX);
    while i < MAX {
        println!("{}", a[i].h);
        i += 1;
    }
}



Aucun commentaire:

Enregistrer un commentaire