Ownership

In Rust each object at a time is represented by a unique variable, and that variable is the owner of the object. The operator = in Rust, by default, is equivalent to the move operator in C++.

For example, this code in Rust :

struct Person 
{
    name : String,
    age : i32
}

fn main()
{
    let p1 = Person {name : "Person 1".to_owned(), age : 10};
    let p2 = p1;    // p2 now owns the object, p1 becomes invalid
    // Uncomment the following line causes a compilation error
    // println!("{} , {} years old", p1.name, p1.age);
    println!("{} , {} years old", p2.name, p2.age);    
}

is equivalent with this code in C++ :

#include <iostream>

using namespace std;

struct Person 
{
    string name;
    int age;
};

int main()
{
    Person p1 = (Person){"Person 1", 10};
    Person p2 = move(p1);    // move object inside p1 to p2
    // Uncomment the following line causes unexpected result
    //cout << p1.name << " , " << p1.age << " years old" << endl;
    cout << p2.name << " , " << p2.age << " years old" << endl;
    return 0;
}

After the = operator in Rust, the original object becomes invalid. In Rust, accessing variable after it no longer owns an object, will raise an error during compilation. In C++, there is no compilation error but the program will encounter some unexpected results. In the above C++ program, if you try to print out information of person p1, you will not see the correct result. In some worse case, you might get an segmentation fault.

In Rust, if a function returns an object, the returned value is the unique owner of that object. This ownership is passed to the variable that takes the returned value of the function call :

struct Person 
{
    name : String,
    age : i32
}

fn createPerson(name : String, age : i32) -> Person
{
    Person{name:name, age:age}                // return the owner of the new object
}

fn main()
{
    let person = createPerson("Person 1".to_owned(), 10);   // 'person' owns the new object
    println!("{} , {} years old", person.name, person.age);    
}

When an object is put into a function, the ownership of the object is passed to the variable inside the function :

fn printInfo(person: Person)
{
    println!("{} , {} years old", person.name, person.age);
}

fn main() 
{
    let person = createPerson("Person 1".to_owned(), 10);
    printInfo(person);
    // println!("{}", person.name);    // error since 'person' no longer owns the object
}

results matching ""

    No results matching ""