struct Student { name: String, age: u32, } impl Student { fn new(name: String, age: u32)…
- User
struct Student { name: String, age: u32, }
impl Student { fn new(name: String, age: u32) -> Student { Student { name, age } }
codefn show(&self) { println!("Student Name: {}, Age: {}", self.name, self.age); }}
fn main() { let student = Student::new(String::from("Alice"), 22); student.show(); }
請詳細說明程式碼
- Assistant
這段程式碼是一個用於定義
Student結構體的 Rust 程式。下面將逐行解釋這段程式碼,每個部分的功能及其意義。結構體定義
ruststruct Student { name: String, age: u32, }struct Student: 這行定義了一個名為Student的結構體(struct)。結構體是一種自定義的數據類型,可以包含多種不同類型的數據。name: String: 在結構體中定義了一個字段name,其類型為String,用於存儲學生的名字。age: u32: 定義了一個字段age,其類型為u32(無符號 32 位整數),用於存儲學生的年齡。
實現區塊
rust - User
enum Vehicle { Car(String), Bike(u32), }
impl Vehicle { fn description(&self) { match self { Vehicle::Car(ref make) => println!("The car is a {}", make), Vehicle::Bike(gears) => println!("The bike has {} gears", gears), } } }
fn main() { let vehicle1 = Vehicle::Car("Toyota".to_string()); let vehicle2 = Vehicle::Bike(21);
codevehicle1.description(); // 修正了拼寫錯誤 vehicle2.description(); let miles_per_gallon: f64 = 25.0; // 增加了小數點以保持一致 let miles = 100.0; // 同上 let gallons_needed = miles / miles_per_gallon; // 確保所有變數型別一致 println!("Gallons needed: {}", gallons_needed); let bike_description = Vehicle::Bike(1); // 修改為 u32 型別 bike_description.description();} 請詳細解釋程式碼
- Assistant