Rust borrowing

Created By: chatGPT

Borrowing in Rust allows you to temporarily access data without taking ownership. This ensures memory safety and eliminates data races at compile time. There are two types of borrowing: immutable and mutable. When you borrow data, you create a reference to it instead of transferring ownership.
fn main() {
    let s = String::from("Hello");
    let r = &s; // immutable borrow
    println!("{}", r);
}
With immutable references, multiple parts of your code can read from the same data at the same time, whereas with mutable references, you can change data but you must ensure that no other references (mutable or immutable) exist at the same time. This enforces strict rules to prevent unexpected changes.
fn main() {
    let mut s = String::from("Hello");
    let r1 = &s; // immutable borrow
    let r2 = &s; // another immutable borrow
    println!("{} and {}", r1, r2);

    // let r_mut = &mut s; // This would be an error
    // println!("{}", r_mut);
}
To mutably borrow a variable, use &mut. Remember that you cannot have an immutable reference and a mutable reference simultaneously. This design helps avoid problems caused by simultaneous access to mutable data.
fn main() {
    let mut s = String::from("Hello");
    let r_mut = &mut s; // mutable borrow
    r_mut.push_str(", world!");
    println!("{}", r_mut);
}
In the following example, attempting to create an immutable reference while a mutable reference is active will result in a compile-time error, enforcing Rust's rules about ownership and borrowing.
fn main() {
    let mut s = String::from("Hello");
    let r_mut = &mut s; // mutable borrow

    // Uncommenting the line below will cause a compile-time error
    // let r = &s; // immutable borrow

    r_mut.push_str(", world!");
    println!("{}", r_mut);
}
Introduction And SetupVariablesData TypesImmutableMutableIntegerFloating PointBooleanCharacterStringArrayTupleVectorSliceHashmapMethodFunctionSyntaxBlock ExpressionIf ExpressionLoopWhile LoopFor LoopMatch ExpressionPattern MatchingOwnershipBorrowingReferencesLifetimesEnumsStructsTraitsImpl BlockGenericType AliasPanicResultOptionError HandlingUnwrappingVariantClosureIteratorAsyncAwaitTrait ObjectModuleCrateAttributeMacroCommentSingle Line CommentMulti Line CommentDoc CommentCargoFormattingOwnership RulesType InferenceShadowingOperatorArithmetic OperatorComparison OperatorLogical OperatorBitwise OperatorAs KeywordConstStaticCopy TraitClone TraitUnsafe CodeFfiCargo ManagementTraits BoundsMatch ArmDerived TraitsClosure CaptureSplit_atIterFilterMapCollectFrom_iterTuple StructUnit TypeNaming ConventionsModule SystemVisibilityPrivatePublicCrate RootUnix Specific FeaturesWindows Specific Features