Rust Note(2)_Data Type II

Rsut Note(2) Data Types II Integer / Float

依照 Data Type 的型別不同, 兩種方法:

  1. 默認型別 : 直接使用系統默認
  2. 指定型別 : 透過 :<type> 指定型別

整數型 Integer


Rust 默認為 i64

Example_1: i8 >> $2^7$-1 = 127, n=8, (n-1)=7, -1 就是扣掉 0
也就是如果型別指定為 i8, 可以接受的最大整數為 -1280127,
如超過 127 就會發生溢位

Example_2: u8 >> $2^8$-1 = 255, n=8, -1 就是扣掉 0
也就是如果型別指定為 u8, 可以接受的最大整數為 0~255,
如超過 255 就會發生溢位

以下範例, 編譯器直接提醒:

1
2
3
4
5
6
7
8
9
10
11
12
$ cargo run
error: literal out of range for `i8`
--> src\main.rs:4:17
|
4 | let x: i8 = 256;
| ^^^
|
= note: `#[deny(overflowing_literals)]` on by default
= note: the literal `256` does not fit into the type `i8` whose range is `-128..=127`
= help: consider using the type `i16` instead

error: could not compile `rust_project` due to previous error

Rust 中的整型

長度 有符號 無符號
8 bits i8 u8
16bits i16 u16
32bits i32 u32
64bits i64 u64
128bits i128 u128
arch isize usize

i 代表有符號整數型: 可接受負數
u 代表無符號整數型: 不可接受負數 !

arch : 可以依照系統架構類型(x86 / x64), 直接判褖套用默認型


以下範例, 編譯器報錯:

1
2
3
4
5
6
7
8
9
 --> src\main.rs:4:17
|
4 | let x: u8 = -126;
| ^^^^ cannot apply unary operator `-`
|
= note: unsigned values cannot be negated

For more information about this error, try `rustc --explain E0600`.
error: could not compile `rust_project` due to previous error

浮點型 (小數) Float

Rust 浮點型默認值為 : f64


浮點型只有兩種型態

  • f32 : 單精度
  • f64 : 雙精度

可以參考這邊 : 單精度雙精度

Note : 20211017_v1.0