#[derive(Debug)] // 給 Person 加上 Debug 特徵,使它能被 println! 印出 struct Person { name: String, height: f64, weight: f64, } fn main() { let p1 = Person { name: String::from("Kyaru"), height: 152.0, weight: 39.0, }; println!("{p1:?}"); } |
let p1 = Person { name: String::from("Kyaru"), height: 152.0, weight: 39.0, } let p2 = p1; println!("{p1:?}"); |
#[derive(Debug, Clone)] // Clone 特徵使得 Person 能夠被複製 struct Person { name: String, height: f64, weight: f64, } fn main() { let p1 = Person { name: String::from("Kyaru"), height: 152.0, weight: 39.0, }; let p2 = p1.clone(); println!("{p1:?}"); println!("{p2:?}"); } |
let mut p1 = Person { name: String::from("Kyaru"), height: 152.0, weight: 39.0, }; let mut p2 = p1.clone(); p1.weight = 50.5; p2.weight = 60.7; println!("{p1:?}"); // Person { name: "Kyaru", height: 152.0, weight: 50.5 } println!("{p2:?}"); // Person { name: "Kyaru", height: 152.0, weight: 60.7 } |
fn say_hello(name_to_display: String) { println!("Hello, {name_to_display}!"); } fn main() { let name = String::from("Kyaru"); say_hello(name); println!("{name}"); } |
fn say_hello(name_to_display: &String) { println!("Hello, {name_to_display}!"); } fn main() { let name = String::from("Kyaru"); say_hello(&name); println!("{name}"); } |
fn say_hello(name_to_display: &String) { println!("Hello, {name_to_display}!"); } fn upgrade(person_name: &mut String) { // 傳入可變引用 if !person_name.ends_with("EX") { person_name.push_str("EX"); } } fn main() { let mut name = String::from("Kyaru"); // 必須是可變變數(shù),才能獲得變數(shù)的可變引用 upgrade(&mut name); // 將 name 以可變的形式借用給 upgrade 函數(shù) say_hello(&name); // 將 name 以不可變的形式借用給 say_hello 函數(shù) } |
fn with_type(mut name: String) -> String { if !name.ends_with(" (cat)") { name.push_str(" (cat)"); } name // 當(dāng) return name; 在函數(shù)最後一行時,可以直接簡化為 name } fn main() { let mut name = String::from("Kyaru"); upgrade(&mut name); let new_name = with_type(name); say_hello(&new_name); } |
let mut name = String::from("Kyaru"); upgrade(&mut name); let new_name = with_type(name); say_hello(&new_name); println!("{name:?}"); // 這句不能被編譯,因為 name 擁有的字串最後交給 new_name 了,現(xiàn)在 name 什麼都沒有 |
let mut name = String::from("Kyaru"); upgrade(&mut name); name = with_type(name); say_hello(&name); println!("{name:?}"); // 這句可以被編譯 |
HackMD 好讀版:https://hackmd.io/@upk1997/rust-ownership-1