如何在Rust中将无符号整数转换为整数?

如何在Rust中将无符号整数转换为整数?,rust,Rust,所以我试图得到一个随机数,但我不希望它作为uint而不是int返回。。。也不确定这个匹配是否正确,但编译器没有走那么远,因为它从未听说过我正在尝试做的事情: fn get_random(max: &int) -> int { // Here we use * to dereference max // ...that is, we access the value at // the pointer location rather

所以我试图得到一个随机数,但我不希望它作为uint而不是int返回。。。也不确定这个匹配是否正确,但编译器没有走那么远,因为它从未听说过我正在尝试做的事情:

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,
        }
}
fn get_random(最大值:&int)->int{
//这里我们使用*来解引用max
//…也就是说,我们在
//指针的位置,而不是
//试着用实际数据做数学题
//指针本身
匹配int::from_uint(rand::random::()%*max+1){
一些(n)=>n,
无=>0,
}
}

来自uint的
不在
std::int
的命名空间中,而是
std::num

原始答复:

使用
as
u32
强制转换为
int
。如果将
uint
u64
转换为
int
,则有可能溢出到负片中(假设您是64位)。从文档中:

uint的大小相当于特定体系结构上指针的大小

这项工作:

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)
}
使用std::rand;
fn main(){
设max=42i;
println!(“{}”,get_random(&max));
}
fn获取\u随机(最大值:&int)->int{
(随机::()作为int)%(*max+1)
}

我喜欢你的答案,而且它是有效的,但我希望有人会来解释为什么from_thing()函数似乎没有按我所想的方式工作。是否有什么东西可以返回一个选项,以便您可以处理溢出?
from_uint
std::num
中删除您在这里做的事情非常危险,您应该知道,函数get_random不会创建有效的随机分布。不要将其用于与安全相关的应用程序!有关良好的解决方案,请参见: