也有英文版文章
Also this tutorial has been written in English
Check out my Medium
結構體(Struct)和枚舉(Enum)是兩個不可分割的存在,今天先來介紹結構體(Struct)。
" Where structs give you a way of grouping together related fields and data, like a Rectangle with its width and height, enums give you a way of saying a value is one of a possible set of values. "- Book of The Rust Programming Language
與其分開宣告變數
let origin_x = 0;
let origin_y = 0;
不如直接定義一個struct來的明白簡潔
struct Point {
x: i32,
y: i32,
}
fn main() {
let origin = Point { x: 0, y: 0 }; // origin: Point
println!("The origin is at ({}, {})", origin.x, origin.y);
}
宣告飲料的struct
struct Drink {
fluid_oz: f64,
}
建一個函式來output
fn print_drinks(the_drink: Drink) {
println!("Oz: {:?}", the_drink.fluid_oz);
}
來到main(),我們設定了飲料的重量,最後呼叫輸出結果的函式
fn main() {
let a: Drink = Drink {
fluid_oz: 10.5,
};
print_drinks(a);
}
struct Drink {
fluid_oz: f64,
}
fn print_drinks(the_drink: Drink) {
println!("Oz: {:?}", the_drink.fluid_oz);
}
fn main() {
let a: Drink = Drink {
fluid_oz: 10.5,
};
print_drinks(a);
}
/*
輸出結果
Oz: 10.5
*/