簡體   English   中英

如何在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::numhttp : from_uint

原始答案:

使用asu32強制轉換為int 如果將uintu64int ,則有可能溢出到負數中(假設您使用的是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM