as 关键字默认为saturating castfn cast(x: f32) -> u8 {
x as u8
}
fn main() {
let too_big = 300.0;
let too_small = -100.0;
let nan = f32::NAN;
println!("too_big_casted = {}", cast(too_big));
println!("too_small_casted = {}", cast(too_small));
println!("not_a_number_casted = {}", cast(nan));
}
too_big_casted = 255
too_small_casted = 0
not_a_number_casted = 0
let x: f32 = 1.0;
let y: u8 = unsafe { x.to_int_unchecked() };
// imagine we have a procedural macro named "mac"
mac!(); // item position, this was what was stable before
// but these three are new:
fn main() {
let expr = mac!(); // expression position
match expr {
mac!() => {} // pattern position
}
mac!(); // statement position
}
for ch in 'a'..='z' {
print!("{}", ch);
}
// Prints "abcdefghijklmnopqrstuvwxyz"
LengthAtMost32,现在已经有了PR在移除这个trait)。Opiton<T>这里的泛型T只能是某个type),有了const generics之后,常量值也能作为泛型参数了!// This is a custom type which is parameterized by a `usize`
pub struct Foo<const N: usize> {
bytes: [u8; N],
}
// This is a trait which has been implemented for arrays of
// any length.
// 通过const generic, 我们可以给任意长度的数组impl某个trait
impl<T: Debug, const N: usize> Debug for [T; N] {
}
impl <const N:usize>中,该值可按字面意义用于填充const泛型。let data = [1, 2, 3, 4, 5, 6];
let sum1 = data.array_chunks().map(|&[x, y]| x * y).sum::<i32>();
assert_eq!(sum1, (1 * 2) + (3 * 4) + (5 * 6));
let sum2 = data.array_chunks().map(|&[x, y, z]| x * y * z).sum::<i32>();
assert_eq!(sum2, (1 * 2 * 3) + (4 * 5 * 6));
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。