Rust的變數型別__Data type

Ashe|||^_^發表於2024-04-08

Every value in Rust is of a certain data type, which tells Rust what kind of data is being specified so it knows how to work with that data. We’ll look at two data type subsets: scalar and compound.在Rust中每一個值都有確定的變數型別,以告知Rust使用的資料是哪一種指定的型別,Rust從而得知如何使用該資料,我們將看到兩種資料型別子集:scalar和compound。

請牢記Rust是一門靜態語言,這意味著在編譯時就必須確定資料的型別。編譯器通常可以根據資料的值或我們如何使用資料來推斷其型別。比如:

// 關鍵字 變數名: 型別註釋 = 變數值
let guess: u32 = "42".parse().expect("Not a number!");

if we don't add the : u32 type annotation shown in the preceding code, Rust will display the following error, which means the complier needs more imformation from us to know which type we want to use.

$ cargo build
   Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0282]: type annotations needed
 --> src/main.rs:2:9
  |
2 |     let guess = "42".parse().expect("Not a number!");
  |         ^^^^^
  |
help: consider giving `guess` an explicit type
  |
2 |     let guess: _ = "42".parse().expect("Not a number!");
  |              +++

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

Scalar Types(標量型別)

A scalar type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, Booleans, and characters. You may recognize these from other programming languages. Let’s jump into how they work in Rust.

Integer types
| Length | Signed | Unsigned |
|--------|--------|----------|
|  8-bit |   i8   |    u8    |
| 16-bit |  i16   |   u16    |
| 32-bit |  i32   |   u32    |
| 64-bit |  i64   |   u64    |
|128-bit | i128   |  u128    |
|  arch  | isize  |  usize   |

Each variant can be either signed or unsigned and has an explicit size. Signed and unsigned refer to whether it’s possible for the number to be negative—in other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned).每一種可以是有符號(具有正負標識)的或無符號的(不具有正負標識),並且具有明確的大小。有符號和無符號是指數字是否可能為負數,也就是說數字需要有符號 || 它只會是正數(因此可以無符號來表示)

相關文章