三秒鐘學一下Rust (1) 初探HelloWorld
3 min readNov 8, 2023
最近在程式社團
引起了許多人的討論,有鑑於此,我也來學習一下
來個新手基本題,如何輸出字串?
fn main() {
println!("Hello, world!");
}
// Hello, world!
然而 使用到印出變數指派就明顯觀察得出不太妙
我不能用以往的方式直接印出字串
// 錯誤的
fn main() {
let hello = "你好";
println!(hello);
}
/*
error: format argument must be a string literal
--> src/main.rs:3:14
|
3 | println!(hello);
| ^^^^^
|
help: you might be missing a string literal to format with
|
3 | println!("{}", hello);
| +++++
*/
而且給出了友好提示
fn main() {
let hello = String::from("你好");
// 使用 {} 包裹變量,並且將它傳遞給 `println!`
println!("{}", hello);
}
// 你好
在 Rust 中,!
指得是一個宏(macro),而不是一個method。
println! 則本來就是 method
它的用法與method略有不同,特別是在它如何處理參數的問題上。
這裡需要將要打印的字符串作為一個參數傳遞給 println!
宏,並且該字符串需要被包裹在大括號中,這是一種格式化輸出的方式
這裡不得不提到 Rust 最核心的概念之一:
擁有權(Ownership)
Ownership Rules
First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them:
- Each value in Rust has an owner.
Rust 中的每個值都有一個擁有者。
- There can only be one owner at a time.
一次只能有一個擁有者。
- When the owner goes out of scope, the value will be dropped.
當擁有者超出範圍時,該值將被刪除。
下一章節再好好地來探討ownership…(還沒講完)
我的腦子差不多又像世紀革命般地爆炸~