Preface
Rust Data Type Conversion
There is no implicit data type conversion in Rust, only explicit data type conversion.
Numeric Literal Conversion to Data Types
- Append the data type after the numeric literal to convert the data type.
Default Values
- The compiler defaults to storing integers as
i32
and floating-point numbers as f64
.
1 2
| let num:i32 = 1; let num:f64 = 1.0;
|
Conversion between Numeric Type Variables
1 2
| let num1:i32 = 1; let num2:f64 = num1 as f64;
|
Defining Data Type Aliases
- Type aliases must follow PascalCase naming convention.
Conversion to Type Aliases
1
| let variable_name = 1 as AliasType;
|
Implementing From
for Custom Structures
1 2 3 4 5 6 7 8 9
| struct StructName { num:i32 }
impl From<i32> for StructName { fn from(item:i32) -> Self { StructName{num:item} } }
|
Converting Data Types using from
1 2
| let s:i32 = 1; let res:StructName = StructName::from(s);
|
Converting Data Types using into
- Converting data types using
into
requires specifying the data type.
1 2
| let s:i32 = 1; let res:StructName = s.into();
|
Conversion between Strings and Numeric Types
Converting Strings to Numeric Types
- As long as the target type implements
FromStr
, you can use parse()
to convert the string to the target type.
1
| let res:i32 = "1".parse().unwrap();
|
Completion
References
Bilibili - Learning for Salary Increase