Comment
โปรแกรมเมอร์ทุกคนพยายามทำให้โค้ดของตนเข้าใจง่าย แต่บางครั้งคำอธิบายเพิ่มเติม ก็จำเป็น ในกรณีเหล่านี้ โปรแกรมเมอร์ทิ้ง comment ไว้ใน source code ของ ตน ซึ่ง compiler จะละเว้น แต่คนที่อ่าน source code อาจพบว่ามีประโยชน์
นี่คือ comment แบบง่าย:
#![allow(unused)]
fn main() {
// hello, world
}
ใน Rust สไตล์ comment ที่ idiomatic เริ่มด้วย slash สองตัว และ comment
ต่อเนื่องจนจบบรรทัด สำหรับ comment ที่ขยายเกินบรรทัดเดียว คุณต้องใส่ //
ในแต่ละบรรทัด แบบนี้:
#![allow(unused)]
fn main() {
// So we're doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what's going on.
}
Comment ยังวางที่ท้ายบรรทัดที่มีโค้ดได้:
Filename: src/main.rs
fn main() {
let lucky_number = 7; // I'm feeling lucky today
}
แต่คุณจะเห็นพวกมันใช้ในรูปแบบนี้บ่อยกว่า โดยมี comment อยู่บรรทัดแยกเหนือ โค้ดที่มัน annotate:
Filename: src/main.rs
fn main() {
// I'm feeling lucky today
let lucky_number = 7;
}
Rust ยังมี comment อีกแบบ คือ documentation comment ซึ่งเราจะพูดถึงใน ส่วน “Publish Crate ไปยัง Crates.io” ของ บทที่ 14