type
status
date
slug
summary
tags
category
icon
password
Prelude:
In the end, all data types in Rust come from these primitive types.
Basic types
- Every value in Rust has a specific data type
- In general, these can be divided into two categories: scalar types and compound types
- Scalar types include:
- Numbers: Signed integers (
i8
,i16
,i32
,i64
,isize
), unsigned integers (u8
,u16
,u32
,u64
,usize
), floating-point numbers (f32
,f64
) - The
isize
andusize
types depend on the architecture of the computer the program is running on: if the CPU is 32-bit, these types are 32-bit; similarly, if the CPU is 64-bit, they are - Rust's default integer type is
i32
- Can overflow, and Rust does not check for this by default. If you encounter incorrect values, make sure to check the type of your numbers.
- Strings: String literals and string slices
- Booleans:
true
andfalse
- Characters: Representing a single Unicode character, stored as 4 bytes
- Unit type: Represented by
()
, with its only value also being()
Be Careful with float
s
See this example:
You might think this would return
true
, but the truth is, the program will panic and quit.- Due to binary precision issues,
0.1 + 0.2
is not exactly equal to0.3
- You can consider using this approach:
(0.1_f64 + 0.2 - 0.3).abs() < 0.00001
NaN
-42.1.sqrt()
will produceNaN
- Any operation involving
NaN
will returnNaN
- Comparing
NaN
will cause the code to panic and crash
- Use
is_nan()
to determine if a value isNaN
Use as
for Type Conversion
In Rust, you can use
as
to convert one type to another.- 作者:Parker Chen
- 链接:www.parkerchenca.com/article/241f0ccf-d7f8-8134-aa27-e1f76e6949cd
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。