Skip to content

Merge dev to main #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions examples/struct-ownership.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
AltaModa Technologies, LLC

struct-ownership example
*/

// This structure contains an 64-bit integer. The entire struct can be stored on the stack.
struct NoHeapElements {
val: i64,
}


// Rust offers `str` which can be on the stack and `String` which is allocated on the heap. Think of
// Rust's `str` as a fixed length char array, and `String` as a dynamically sized char array.
// This structure contains a String which is allocated on the heap. An instance of this struct may be
// on the stack and `desc` is a reference to the heap-allocated String.
struct AllHeapElements {
desc: String,
}


fn main () {

// A struct that does not use the heap
let n = NoHeapElements { val: 74 };
println!("\nThe variable `n` is type NoHeapElements");
println!("`n` and elements of NoHeapElements are on the stack");
println!("n.val: {}", n.val);

let a = AllHeapElements {
desc: "String (not str) is always on the heap".to_string(),
};
println!("\nThe variable `a` is type AllHeapElements");
println!("`a` is on the stack; elements of AllHeapElements are on the heap");
println!("a.desc = {}", a.desc);

// This code fails to compile because `a2` has taken ownership of
// the struct reference from `a`. Rust refers to this as
// ownership _moving_ from `a` to `a2`. Uncommenting these lines
// see the "borrow after move" error on compilation.
// let a2 = a;
// println!("a.desc = {}", a.desc);

println!();
}