tl; dr: "owning" types in Rust is not some kind of magic, and they are certainly not hardcoded into the compiler or language. They are only types that are written in a certain way (they do not implement Copyand probably have a destructor), and they have a certain semantics that are provided through incompatibility and a destructor.
In its basic ownership mechanism, Rust is very simple and has very simple rules.
First of all, determine what a movement is. It's simple - the value is considered moved when it becomes available under the new name and ceases to be available under the old name:
struct X(u32);
let x1 = X(12);
let x2 = x1;
The same thing happens when you pass a value to a function:
fn do_something(x: X) {}
let x1 = X(12);
do_something(x1);
, - , , . , - , .
, , , , . , , Vec Box, . Drop trait:
struct X(u32);
impl Drop for X {
fn drop(&mut self) {
println!("Dropping {}", x.0);
}
}
{
let x1 = X(12);
}
, Copy trait, - , :
#[derive(Copy, Clone)] struct X(u32);
let x1 = X(12);
let x2 = x1;
- x2 x1.
Copy - , Copy Drop. ( &mut, *const *mut raw ) Rust, , , Copy. , , Vec Box, Copy - , , .
Copy - , . Rust . , - -, , "Box<T> T", , , . , Vec Box, Copy , , , () , , (, , ..).
, "" . Rust, . , C API . "" Rust , , , :
extern {
fn create_widget() -> *mut WidgetStruct;
fn destroy_widget(w: *mut WidgetStruct);
fn use_widget(w: *mut WidgetStruct) -> u32;
}
struct Widget(*mut WidgetStruct);
impl Drop for Widget {
fn drop(&mut self) {
unsafe { destroy_widget(self.0); }
}
}
impl Widget {
fn new() -> Widget { Widget(unsafe { create_widget() }) }
fn use_it(&mut self) -> u32 {
unsafe { use_widget(self.0) }
}
}
, Widget , *mut WidgetStruct.