[英]How do I add a signed integer to an unsigned integer in Rust?
[英]How do I convert an unsigned integer to an integer in Rust?
因此,我嘗試獲取一個隨機數,但我不希望它以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,
}
}
from_uint
不在std::int
的命名空間中,而是std::num
: http : from_uint
原始答案:
使用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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.