[英]find the max between 0 and a sum of an unsigned int with a signed int
I'm trying to write a function which will take an X position and an offset.我正在尝试编写一个 function ,它将采用 X position 和一个偏移量。 This offset can be either negative or positive so I need it to be signed.这个偏移量可以是负数也可以是正数,所以我需要对其进行签名。 So if I pass it X = 0
and ofs = -3
I need the function to set X
to 0
, also, or if I pass it X = 0
, ofs = 6
and uppr_lmt = 5
I need it set it to 5
因此,如果我通过它X = 0
和ofs = -3
我需要 function 也将X
设置为0
,或者如果我通过它X = 0
, ofs = 6
和uppr_lmt = 5
我需要将它设置为5
fn test(x: &mut u32, ofs: i32, uppr_lmt: u32) {
use std::cmp::max;
if ofs < 0 {
x = max(0, x + ofs);
} else {
x = max(uppr_lmt, x + ofs);
}
}
However, in this code rust complains about adding an i32
to an &mut u32
and 0
and uppr_lmt
not being of type &mut u32
.但是,在此代码中 rust 抱怨将i32
添加到&mut u32
u32 和0
并且uppr_lmt
不是&mut u32
u32 类型。 How can I go about fixing this?我该如何解决这个问题? I'm still fairly new to Rust and I'm not used to type conversions.我对 Rust 还是很陌生,而且我不习惯类型转换。
The below code is returning a u32 rather than mutating x value.下面的代码返回一个 u32 而不是改变 x 值。 Note that we are having extra conversions to i64 because in an i32, the -3 is going to be considered greater than 0 because of how negative numbers are stored (MSB is 1 for negatives while MSB is taken as 2 power for u32).请注意,我们对 i64 进行了额外的转换,因为在 i32 中,-3 将被视为大于 0,因为负数的存储方式(MSB 为 1 表示负数,而 MSB 被视为 u32 的 2 次方)。 Note that I have used min here for else case because otherwise, for 0,5,6 passed to function, it returns 6 because max of 5 and 6 is 6 which is not what you expected from your question请注意,我在 else 情况下使用了 min ,否则,对于传递给 function 的 0、5、6,它返回 6,因为 5 和 6 的最大值为 6,这不是您对问题的期望
fn test(x: u32, ofs: i32, uppr_lmt: u32) -> u32 {
use std::cmp::{max,min};
let y;
if ofs < 0 {
y = max(0, x as i64 + ofs as i64);
} else {
y = min(uppr_lmt as i64, x as i64 + ofs as i64);
}
y as u32
}
Instead of i64, you can also use i32 like this assuming inputs are in i32 range and not u32 range (if the number plus offset is less than 2^31 - 1 only)除了 i64,您还可以像这样使用 i32,假设输入在 i32 范围内而不是 u32 范围内(如果数字加上偏移量仅小于 2^31 - 1)
fn test(x: u32, ofs: i32, uppr_lmt: u32) -> u32 {
use std::cmp::{max,min};
let y;
if ofs < 0 {
y = max(0, x as i32+ ofs);
} else {
y = min(uppr_lmt as i32, x as i32+ ofs);
}
y as u32
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.