Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1Tips¶
Integer types:
u8(0 to 255),i8(-128 to 127),u16(0 to 65,535),i16(-32,768 to 32,767),u32(0 to 4,294,967,295),i32(-2,147,483,648 to 2,147,483,647),u64,i64.
Notice thati32is the default type for integers.
Float types:
f32,f64(default)Boolean:
boolCharacter:
charTuple
Array
Type Cast¶
Cast without loss using
type::fromorobj.into.cast with possible loss using
asImplementing
Fromwill result in theIntoimplementation but not vice-versa.
For more discussions, please refer to How do I convert between numeric types safely and idiomatically?.
Integers¶
0xFFFF as u80xFFFF as u8
^^^^^^
literal out of range for `u8`
help: consider using the type `u16` insteadlet x: i64 = 1;
i32::from(x)i32::from(x)
^^^^^^^^^ the trait `From<i64>` is not implemented for `i32`
the trait bound `i32: From<i64>` is not satisfied
help: the following implementations were found:
<i32 as From<NonZeroI32>>
<i32 as From<bool>>
<i32 as From<i16>>
<i32 as From<i8>>
and 2 otherslet x: usize = 1;
u64::from(x)u64::from(x)
^^^^^^^^^ the trait `From<usize>` is not implemented for `u64`
the trait bound `u64: From<usize>` is not satisfied
help: the following implementations were found:
<u64 as From<NonZeroU64>>
<u64 as From<bool>>
<u64 as From<u16>>
<u64 as From<u32>>
<u64 as From<u8>>let x: u64 = 1;
u64::from(x)1let x: i64 = 1;
x1x as i321let x1: u8 = 1;
x11let x2: i8 = 1;
x21let x3: i32 = 1;
x31Comparison and Ordering¶
Ordering::Less, Ordering::Equal and Ordering::Greater
are converted to -1, 0 and 1
when converting an Ordering enum to an integer.
1.cmp(&2)Less1.cmp(&2) as i32-12.cmp(&2) as i3203.cmp(&2) as i321Type Suffix for Literal Integers¶
1 << 541 << 54
^^^^^^^ attempt to shift left by `54_i32`, which would overflow
this arithmetic operation will overflow1u64 << 5418014398509481984Bit Operations on Integers¶
Mathematic operators
+,-,*and/have high precedence than bit operators (&,|,!,^,<<,>>, etc)!!! It is suggested that you use parentheses if you are not sure about the precedences.
let x: u64 = (1u64 << 52) - 1;
x4503599627370495format!("{:b}", x)"1111111111111111111111111111111111111111111111111111"i32::from(1)1count_ones¶
Count ones in an integer.
let n: u64 = 0b100_0000;
n.count_ones()12i16 << 14-2i16 << 1-4let mut x = -10i16;
x <<= 1;
x-20Floating Numbers¶
NaN Is Tricky¶
f64::NANNaN1.0 > f64::NANfalse1.0 == f64::NANfalse1.0 < f64::NANfalse1.0 + f64::NANNaNtuple¶
let t = (1, "hello");
t(1, "hello")