变量遮蔽 shadowing
fn type_of<T>(_: &T) -> String {
format!("{}", std::any::type_name::<T>())
}
fn print<T: std::fmt::Display>(x: &T) {
println!("{}\tsize({}): {}", type_of(x), std::mem::size_of_val(x), x);
}
fn main() {
let x = 1u32 + 2;
print(&x);
// 变量遮蔽 shadowing
let x = "hello world!";
print(&x);
// warning 常量需要大写
// 常量不能被遮蔽 shadowing
// 常量需要显式指定类型
const Y: i32 = 12;
let x = Y;
print(&x);
const Z: &str = "hello world!";
let x = Z;
print(&x)
}
Range
use std::ops::{Range, RangeInclusive};
fn main() {
assert_eq!((1..5), Range{ start: 1, end: 5 });
assert_eq!((1..=5), RangeInclusive::new(1, 5));
}
类型转换 as
fn main() {
let v: u16 = 38u8 as u16;
}
数值类型
fn type_of<T>(_: &T) -> String {
format!("{}", std::any::type_name::<T>())
}
fn print<T: std::fmt::Display>(x: &T) {
println!("{}\tsize({}): {}", type_of(x), std::mem::size_of_val(x), x);
}
fn main() {
let x = 1u32 + 2;
print(&x);
let x = 1i32 - 2;
print(&x);
let x = 1i8 - 2;
print(&x);
let x = 3 * 50;
print(&x);
let x = 9.6 / 3.2;
print(&x);
let x = 3 * 50;
print(&x);
let x = 24 % 5;
print(&x);
let x = true && false;
print(&x);
let x = true & false;
print(&x);
}
字符,是Unicode编码,所有字符都是4个字节
fn type_of<T>(_: &T) -> String {
format!("{}", std::any::type_name::<T>())
}
fn print<T: std::fmt::Display>(x: &T) {
println!("{}\tsize({}): {}", type_of(x), std::mem::size_of_val(x), x);
}
fn main() {
let x = 'a';
print(&x);
let x = '中';
print(&x);
let x = '😱';
print(&x);
let x = 'é';
print(&x);
}