Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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 that i32 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 or obj.into.

  • cast with possible loss using as

  • Implementing From will result in the Into implementation but not vice-versa.

For more discussions, please refer to How do I convert between numeric types safely and idiomatically?.

From and Into

Why From trait vs Into trait?

Cast a smaller integer to a larger integer

Number Conversions

Integers

0xFFFF as u8
^^^^^^ 
literal out of range for `u8`
help: consider using the type `u16` instead
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 others
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>>
1
1
1
1
1
1

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.

Less
-1
0
1

Type Suffix for Literal Integers

1 << 54
^^^^^^^ attempt to shift left by `54_i32`, which would overflow
this arithmetic operation will overflow
18014398509481984

Bit Operations on Integers

  1. 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.

4503599627370495
"1111111111111111111111111111111111111111111111111111"
1

count_ones

Count ones in an integer.

1
4
-4
-20

Floating Numbers

NaN Is Tricky

NaN
false
false
false
NaN

tuple

(1, "hello")