DEV Community

Anuchit Prasertsang
Anuchit Prasertsang

Posted on

1 1

Rust | References and Borrowing

การอ้างถึง (Reference)

การใช้ References ทำให้เราสามารถเข้าถึงข้อมูลได้โดยที่ไม่ต้องเป็นเจ้าของข้อมูลนั้นก่อน

  • '&' ampersands คือเครื่องหมายการอ้างถึงข้อมูล
  • การใช้เครื่องหมาย '&' ทำให้เราสามารถเข้าถึงข้อมูลได้โดยไม่ต้องเปลี่ยนเจ้าของมาเป็นเรา

ตัวอย่าง

let s = String::from("data");
println!(&s);
Enter fullscreen mode Exit fullscreen mode

s ยังคงเป็นเจ้าของข้อมูล "data" อยู่ ฟังก์ชั่น println แค่ขอยืมการเข้าถึงข้อมูลนั้นเพื่อทำการปริ้น หลังจาก println ทำงานเสร็จ s ก็กลับมาถือครองข้อมูล "data" ดังเดิม

  • ฟังก์ชัน println จะสามารถอ้างถึง ข้อมูล "data" ได้ตราบเท่าที่พารามิเตอร์ของฟังก์ชัน println ชีวิตอยู่

การยืม (Borrowing)

การยืมใช้สำหรับการขอสิทธิเข้าถึงข้อมูลดังตัวอย่างด้านบน
หากเราต้องการยืมด้วย และมีสิทธิในการแก้ไขด้วย ต้องใช้การยืม แบบ &mut s
ทั้งนี้ s ต้องประกาศเป็น mut ถึงจะสามารถทำได้

fn main(){
    let mut s = String::from("data");
    print(&mut s); // ยืมแบบสามารถแก้ไขข้อมูล "data" ได้ด้วย
    println!("in main: {}", s);
}

fn print(n: &mut String) {
    println!("in print : {}", n);
    n.push_str(" change here");
}
Enter fullscreen mode Exit fullscreen mode

ผลลัพท์

in print : data
in main: data change here
Enter fullscreen mode Exit fullscreen mode

โปรแกรมสามารถยืมได้แค่ทีละตัวแปร ไม่สามารถยืมได้พร้อมกันหลายตัวแปรได้ถ้าหากมันเป็น mut คือข้อมูลที่สามารถเปลี่ยนแปลงได้ ตามกฎ

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay