Rust cơ bản
Rust Data Types: Integers, Floats, bool and char
Pick the right type for each value and convert between numbers with as.
Bạn sẽ học được gì
- u8, i32, i64 and f64
- bool and char
- Converting with as
Value → type
30u8, a small whole number-4.5f64, a decimal numbertruebool'A'charEvery value has a type known at compile time
Rust is statically typed: every value has a type that the compiler knows. Integers come in sizes such as u8 and i64, f64 holds decimal numbers, bool is true or false, and char is one Unicode character.
Rust never converts numbers silently, so age as f64 is needed before adding a float. Underscores in 1_000_000 only make the number easier to read. u8::MAX is the largest value a u8 can hold.
Những điểm quan trọng
- Integer types say their size: u8 holds 0 to 255.
- Rust never converts numbers silently: write age as f64.
- char is one Unicode character, written in single quotes.
Ví dụ Rust chạy được
Rust
main.rs
fn main() {
let age: u8 = 30;
let temperature: f64 = -4.5;
let is_ready: bool = true;
let grade: char = 'A';
let big = 1_000_000i64;
let total = age as f64 + temperature;
println!("{age} {temperature} {is_ready} {grade} {big}");
println!("total = {total}");
println!("u8 max = {}", u8::MAX);
}
30 -4.5 true A 1000000
total = 25.5
u8 max = 255Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Body Mass Index Compute BMI from weight and height. Dễ
- Trung Bình Của Ba Số Tính trung bình cộng của ba số nguyên. Dễ