summaryrefslogtreecommitdiff
path: root/rust/ownership.rs
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
committerCarlos Maiolino <[email protected]>2025-07-10 22:24:20 +0200
commit869e68986aa8f69af6e7842260a68d1e5c6f796f (patch)
tree63b6b5ffc3d19414233d4629a533c0d9bf3cbf72 /rust/ownership.rs
parent20834dcc57537cd95260a4a22f5d91a027adfd35 (diff)
Add a bunch of code
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/ownership.rs')
-rw-r--r--rust/ownership.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/rust/ownership.rs b/rust/ownership.rs
new file mode 100644
index 0000000..3a96743
--- /dev/null
+++ b/rust/ownership.rs
@@ -0,0 +1,74 @@
+// Rules of ownership:
+//
+// 1 - each value has an owner
+// 2 - only one owner allowed
+// 3 - if owner goes out of scope, value will be freed
+//
+// Scopes: Global, local -> Similar to C
+
+fn main() -> () {
+
+ let h = "Hello"; // s is the owner
+ let s = get_string();
+
+// let s2 = s; // This only copies the pointer value, not the
+ // String data type
+ //
+ // This essentially violates the ownership rule of
+ // a single owner.
+ // Because of that, rust compiler drops the ownership
+ // of the original variable 's', only s2 owns the pointer
+ // now.
+
+ let s2 = s.clone(); // Deep copy String s
+
+ println!("{}", h);
+
+ println!("{}", s2);
+
+ println!("{}", s); // generates an error due to ownership if .clone ain't used
+
+
+ // Transferring ownership
+
+ take_ownership(s); // 's' value is moved to the function. From now on, 's' is
+ // no longer valid here.
+
+// println!("{}", s); // KABOOM
+
+ // give_ownership allocate and return us a
+ // String type, giving s3 ownership of the
+ // allocated String.
+ // s3 belongs to this scope now.
+ let s3 = give_ownership();
+
+ // Sending and getting ownership back
+
+ let s5 = String::from("This is mine");
+ let s5 = give_me_back(s5); // I'm shadowing s5 here, but I could have used
+ // something else
+
+ println!("{} {}", s3, s5);
+
+} // s - only valid to here
+
+fn give_me_back(s: String) -> String {
+
+ return s;
+}
+
+fn give_ownership() -> String {
+
+ // The ownership of the String allocated here
+ // will be transferred to the caller.
+ return String::from("Jumento celestino");
+}
+fn take_ownership(s: String) {
+ println!("Ownership transfer completed. \n{}", s);
+
+ // Reaching end of this scope will free 's'
+}
+
+fn get_string() -> String {
+ return String::from("Ronaldo");
+}