「Rust」X Practice
Rust Practice 的一些练习题
变量绑定与解构
变量作用域/生命周期
// 修复错误
fn main() {
let x = define_x();
println!("{}, world", x);
}
fn define_x() {
let x = "hello";
}
函数需要存在一个返回值,并且声明返回类型,但是要避免 悬垂引用。
//返回String
fn define_x() -> String {
let x = "hello";
x.to_string()
}
//或者 声明 生命周期
fn define_x<'a>() -> &'a str {
let x = "hello";
x
}
未使用的变量
fn main() {
let x = 1;
}
// compiler warning: unused variable: `x`
可以在变量前加_
,忽略未使用的变量。但是和_
不同,_x
仍然会将值绑定到变量
fn main(){
let _x = 1;
}
//可以使用 # 声明
#[allow(unused_variables)]
fn main(){
let x = 1;
}
基本类型
//以下函数可以获取传入参数的类型,返回类型的字符串形式
fn type_of<T>(_: &T) -> String {
format!("{}", std::any::type_name::<T>())
}
数值类型
//使得可以运行
fn main() {
assert!(0.1+0.2==0.3);
}
Rust默认的浮点数是f64
的,相当于C中的double
。
使用
abs()
时,未指定数据类型会报错:can't call method
abson ambiguous numeric type '{float}'
fn main(){
assert!((0.1_f64 + 0.2 - 0.3).abs() < 0.001);
}
//使用 f32
fn main(){
assert!(0.1_f32 + 0.2_f32 == 0.3_f32);
}