Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Ownership / Move

Ownership / Move

Rust's ownership system enforces a unique rule: every value has exactly one owner. This guarantees memory safety at compile time. When the owner goes out of scope, the value is automatically freed.

Syntax

// Ownership move
let variable1 = value;
let variable2 = variable1; // Ownership of variable1 moves to variable2 (variable1 becomes invalid).

// Moving ownership into a function
fn function_name(arg: Type) { ... }
function_name(variable); // Ownership of variable moves into the function.

// Explicitly free memory
drop(variable);

Overview

RuleDescription
Single ownerEach value has exactly one owning variable at any given time.
Freed at scope endWhen the owner goes out of scope, the value's memory is automatically freed.
Move semanticsAssignment or passing to a function moves ownership, making the original variable unusable.
drop()Used to immediately free a variable that holds ownership.

Sample Code

fn take_ownership(s: String) {
    println!("{}", s);
} // s is freed here.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership of s1 moves to s2.
    // println!("{}", s1); // Error: s1 is no longer valid.
    println!("{}", s2); // Prints "hello".

    let s3 = String::from("world");
    take_ownership(s3); // Ownership of s3 moves into the function.
    // println!("{}", s3); // Error: s3 is no longer valid.

    // Immediately free s4 with drop().
    let s4 = String::from("drop me");
    drop(s4);
    // println!("{}", s4); // Error: s4 has already been freed.

    // Types that implement the Copy trait are copied instead of moved.
    let x = 5;
    let y = x; // x is still valid.
    println!("x={}, y={}", x, y); // Both are usable.
}

Details

Rust's ownership system guarantees memory safety without a garbage collector. When a value goes out of scope, drop() is called automatically and the memory is freed (the RAII pattern).

Using a variable after its ownership has been moved causes a compile error. If you need to use a value in multiple places, use borrowing (& references) or clone().

Types that implement the Copy trait — such as integers, floating-point numbers, booleans, and chars — are copied on assignment, so the original variable remains valid.

If you find any errors or copyright issues, please .