How do I convert an unsigned integer to an integer in Rust? -
so i'm trying random number, i'd rather not have come uint instead of int... not sure if match right, either, compiler doesn't far because it's never heard of from_uint thing i'm trying do:
fn get_random(max: &int) -> int { // here use * dereference max // ...that is, access value @ // pointer location rather // trying math using actual // pointer match int::from_uint(rand::random::<uint>() % *max + 1) { some(n) => n, none => 0, } }
from_uint
not in namespace of std::int
, std::num
: http://doc.rust-lang.org/std/num/fn.from_uint.html
original answer:
cast u32
int
as
. if cast uint
or u64
int
, risk overflowing negatives (assuming on 64 bit). docs:
the size of uint equivalent size of pointer on particular architecture in question.
this works:
use std::rand; fn main() { let max = 42i; println!("{}" , get_random(&max)); } fn get_random(max: &int) -> int { (rand::random::<u32>() int) % (*max + 1) }
Comments
Post a Comment