Refactor function parameters in move_semantics6.rs

This commit is contained in:
Rock070 2023-12-17 16:37:19 +08:00
parent 1a956075a0
commit 778452a921

View File

@ -5,24 +5,22 @@
// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand // Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand
// for a hint. // for a hint.
// I AM NOT DONE
fn main() { fn main() {
let data = "Rust is great!".to_string(); let data = "Rust is great!".to_string();
get_char(data); get_char(&data); // 修改這裡,傳遞一個參考
string_uppercase(&data); string_uppercase(data); // `data` 的所有權被移動到 `string_uppercase`
} }
// Should not take ownership // 現在 `get_char` 接收一個對 `String` 的不可變參考
fn get_char(data: String) -> char { fn get_char(data: &String) -> char {
data.chars().last().unwrap() data.chars().last().unwrap()
} }
// Should take ownership // `string_uppercase` 保持不變,因為它需要取得所有權
fn string_uppercase(mut data: &String) { fn string_uppercase(mut data: String) {
data = &data.to_uppercase(); data = data.to_uppercase();
println!("{}", data); println!("{}", data);
} }