R

Propriété & Emprunt

Rust Syntax Guide

Système de propriété et d'emprunt de Rust

Propriété & Emprunt

Système de propriété et d'emprunt de Rust

Rust propriété & emprunt (rust)
        
          // Ownership basics
fn main() {
    // Variable binding
    let s1 = String::from("hello");  // s1 owns the string
    let s2 = s1;                     // Ownership moves to s2, s1 is invalid

    // println!("{}", s1);           // This would cause a compile error

    println!("s2: {}", s2);          // s2 owns the string

    // Borrowing
    let s3 = String::from("world");
    let len = calculate_length(&s3);  // Borrow s3 (immutable reference)

    println!("Length of '{}' is {}", s3, len);  // s3 is still valid

    // Mutable borrowing
    let mut s4 = String::from("hello");
    change_string(&mut s4);          // Mutable borrow

    println!("Changed: {}", s4);

    // Multiple immutable borrows
    let r1 = &s4;
    let r2 = &s4;
    // let r3 = &mut s4;  // This would cause a compile error

    println!("{} and {}", r1, r2);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

fn change_string(s: &mut String) {
    s.push_str(" world");
}

// Ownership in functions
fn takes_ownership(some_string: String) {
    println!("{}", some_string);
} // some_string goes out of scope and is dropped

fn makes_copy(some_integer: i32) {
    println!("{}", some_integer);
} // some_integer goes out of scope, but nothing special happens

fn gives_ownership() -> String {
    let some_string = String::from("yours");
    some_string
}

fn takes_and_gives_back(a_string: String) -> String {
    a_string  // Return ownership
}
        
      

Explanation

Le système de propriété de Rust assure la sécurité mémoire sans garbage collection. Chaque valeur a un propriétaire. Les références permettent l'emprunt sans transférer la propriété.

Common Use Cases

  • Programmation système
  • Code critique pour les performances
  • Systèmes embarqués
  • WebAssembly

Related Rust Syntax

Master Propriété & Emprunt in Rust

Understanding Propriété & Emprunt is fundamental to writing clean and efficient Rust code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Propriété & Emprunt effectively in your Rust projects.

Key Takeaways

  • Programmation système
  • Code critique pour les performances
  • Systèmes embarqués