In [ ]:
:timing
:sccache 1
Tips¶
- 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 thati32
is the default type for integers.
- Float types:
f32
,f64
(default) - Boolean:
bool
- Character:
char
- Tuple
- Array
Type Cast¶
- Cast without loss using
type::from
orobj.into
. - cast with possible loss using
as
- Implementing
From
will result in theInto
implementation but not vice-versa.
For more discussions, please refer to How do I convert between numeric types safely and idiomatically?.
Integers¶
In [2]:
0xFFFF as u8
In [3]:
let x: i64 = 1;
i32::from(x)
In [6]:
let x: usize = 1;
u64::from(x)
In [5]:
let x: u64 = 1;
u64::from(x)
Out[5]:
In [2]:
let x: i64 = 1;
x
Out[2]:
In [4]:
x as i32
Out[4]:
In [5]:
let x1: u8 = 1;
x1
Out[5]:
In [7]:
let x2: i8 = 1;
x2
Out[7]:
In [10]:
let x3: i32 = 1;
x3
Out[10]:
Comparison and Ordering¶
Ordering::Less
, Ordering::Equal
and Ordering::Greater
are converted to -1, 0 and 1
when converting an Ordering
enum to an integer.
In [3]:
1.cmp(&2)
Out[3]:
In [4]:
1.cmp(&2) as i32
Out[4]:
In [5]:
2.cmp(&2) as i32
Out[5]:
In [6]:
3.cmp(&2) as i32
Out[6]:
Type Suffix for Literal Integers¶
In [8]:
1 << 54
In [9]:
1u64 << 54
Out[9]:
Bit 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.
In [10]:
let x: u64 = (1u64 << 52) - 1;
x
Out[10]:
In [11]:
format!("{:b}", x)
Out[11]:
In [2]:
i32::from(1)
Out[2]:
count_ones¶
Count ones in an integer.
In [11]:
let n: u64 = 0b100_0000;
n.count_ones()
Out[11]:
In [2]:
2i16 << 1
Out[2]:
In [3]:
-2i16 << 1
Out[3]:
In [5]:
let mut x = -10i16;
x <<= 1;
x
Out[5]:
Floating Numbers¶
NaN Is Tricky¶
In [2]:
f64::NAN
Out[2]:
In [3]:
1.0 > f64::NAN
Out[3]:
In [4]:
1.0 == f64::NAN
Out[4]:
In [5]:
1.0 < f64::NAN
Out[5]:
In [6]:
1.0 + f64::NAN
Out[6]:
tuple¶
In [3]:
let t = (1, "hello");
t
Out[3]:
References¶
In [ ]: