add ownership and borrowing testing
This commit is contained in:
7
ownership/Cargo.lock
generated
Normal file
7
ownership/Cargo.lock
generated
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ownership"
|
||||||
|
version = "0.1.0"
|
||||||
6
ownership/Cargo.toml
Normal file
6
ownership/Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "ownership"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
34
ownership/src/main.rs
Normal file
34
ownership/src/main.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
fn main() {
|
||||||
|
let a ="Hello".to_string();
|
||||||
|
let b = a;
|
||||||
|
|
||||||
|
//println!("{}",a); This will error because a no longer owns the string
|
||||||
|
println!("{}",b);
|
||||||
|
|
||||||
|
//simple types like number characters and booleans are copied not moved
|
||||||
|
let c = 5;
|
||||||
|
let d = c;
|
||||||
|
println!("{}",c);
|
||||||
|
println!("{}",d);
|
||||||
|
|
||||||
|
// when ownership does not need to be moved clone can be used.
|
||||||
|
let e ="Test".to_string();
|
||||||
|
let f = e.clone();
|
||||||
|
|
||||||
|
println!("{}",e);
|
||||||
|
println!("{}",f);
|
||||||
|
|
||||||
|
// references in cpp is called borrowing in rust
|
||||||
|
let g = String::from("Reference test");
|
||||||
|
let h = &g;
|
||||||
|
|
||||||
|
println!("{}", g);
|
||||||
|
println!("{}", h);
|
||||||
|
|
||||||
|
// mutable references
|
||||||
|
let mut i = String::from("Mutable Reference test");
|
||||||
|
let j = &mut i;
|
||||||
|
j.push('!');
|
||||||
|
|
||||||
|
println!("{}", j);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user