พื้นฐาน Rust

Rust Functions and Return Values

Define functions with typed parameters and return a value without writing return.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Parameters with types
  • Return type after ->
  • The last expression is returned
area(4, 5)
  1. 14, 5arguments
  2. 2width * heightthe body runs
  3. 320returned to the caller

Values go in, one value comes out

A function groups code under a name. In Rust you write the type of every parameter and, after ->, the type of the value the function returns.

The last expression of a function is its return value when it has no semicolon, so width * height is returned without the return keyword. format! builds a String the same way println! prints one.

ประเด็นสำคัญ

  1. Every parameter needs a type.
  2. -> u32 says what the function returns.
  3. A final expression without ; is the return value.

ตัวอย่าง Rust ที่รันได้

Rust
รันโค้ด →
main.rs
fn area(width: u32, height: u32) -> u32 {
    width * height
}

fn describe(name: &str, size: u32) -> String {
    format!("{name} covers {size} square meters")
}

fn main() {
    let size = area(4, 5);
    println!("{}", describe("The room", size));
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
The room covers 20 square meters

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Binary Search →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด