user1949917
user1949917

Reputation:

How do I convert an unsigned integer to an integer in Rust?

So I'm trying to get a random number, but I'd rather not have it come back as uint instead of int... Not sure if this match is right, either, but the compiler doesn't get that far because it's never heard of this from_uint thing I'm trying to do:

fn get_random(max: &int) -> int {
        // Here we use * to dereference max
        // ...that is, we access the value at 
        // the pointer location rather than
        // trying to do math using the actual
        // pointer itself
        match int::from_uint(rand::random::<uint>() % *max + 1) {
                Some(n) => n,
                None => 0,
        }
}

Upvotes: 5

Views: 12251

Answers (1)

Jin
Jin

Reputation: 13463

from_uint is not in the namespace of std::int, but std::num: http://doc.rust-lang.org/std/num/fn.from_uint.html

Original answer:

Cast a u32 to int with as. If you cast uint or u64 to int, you risk overflowing into the negatives (assuming you are on 64 bit). From the docs:

The size of a uint is equivalent to the size of a pointer on the 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>() as int) % (*max + 1)
}

Upvotes: 1

Related Questions