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

5

我想要获取一个随机数,但是我不希望它以uint而不是int的形式返回...我不确定这个匹配是否正确,但编译器无法进行这个from_uint操作,因为它从未听说过:

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,
        }
}
1个回答

1

from_uint不在std::int的命名空间中,而在std::num中: http://doc.rust-lang.org/std/num/fn.from_uint.html

原始答案:

使用asu32转换为int。如果将uintu64强制转换为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)
}

我喜欢你的答案,它也起作用了,但我希望有人能够解释一下为什么 from_thing() 函数似乎没有按照我预期的方式工作。 - user1949917
有没有返回Option<int>的方法,以便您可以处理溢出? - Andrew Wagner
1
from_uintstd::num 中移除。 - KindDragon
你在这里做的事情非常危险,你应该知道你的函数 get_random 不会创建有效的随机分布。不要将其用于安全相关的应用程序!有一个好的解决方案,请参见:http://doc.rust-lang.org/num/rand/index.html - Tijs Maas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接