Skip to content

Instantly share code, notes, and snippets.

@CarterTsai
Created April 13, 2020 14:58
Show Gist options
  • Save CarterTsai/1ced1bb8e44e0420b711ec99bc446eee to your computer and use it in GitHub Desktop.
Save CarterTsai/1ced1bb8e44e0420b711ec99bc446eee to your computer and use it in GitHub Desktop.
rust struct
fn main() {
// 結構
// https://doc.rust-lang.org/rust-by-example/custom_types/structs.html
#[derive(Debug)]
struct User {
username: String,
email: String,
}
let user1 = User {
email: String::from("[email protected]"),
username: String::from("anotherusername567"),
};
println!("\n1. basically");
println!("user1 => {:?}", user1);
println!("user1.email => {}", user1.email);
println!("user1.username => {}", user1.username);
let user2 = User {
email: String::from("[email protected]"),
..user1
};
println!("使用..語法指定了剩餘未設置的欄位與給定對應字段相同的值");
println!("user2 => {:?}", user2);
println!("user2.email => {}", user2.email);
println!("user2.username => {}", user2.username);
// A tuple struct
#[derive(Debug)]
struct CarPrice(String, u32);
let carprice = CarPrice(String::from("Benz"), 2000);
println!("\n2. A tuple struct");
println!("carprice => {:?}", carprice);
println!("car name {} , car price {}", carprice.0, carprice.1);
#[derive(Debug)]
struct CarBox {
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
top: CarPrice,
bottom: CarPrice,
};
let _box = CarBox {
top: CarPrice(String::from("Benz"), 2000),
bottom: CarPrice(String::from("BMW"), 1500),
};
println!("Structs can be reused as fields of another struct");
println!("car box => {:?}", _box);
// Destructure a tuple struct
let CarPrice(ss, pp) = carprice;
println!("\ndestructure a tuple struct");
println!("car name => {}", ss);
println!("car price => {}", pp);
// A unit struct
#[derive(Debug)]
struct Nil;
let nil = Nil;
println!("\n3. A unit struct");
println!("nil => {:?}", nil);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment