1+ // RUN THE CODE - cargo run --example 03_ownership_and_borrowing
2+
13use std:: io;
24
3- fn main ( ) -> io:: Result < ( ) > {
4-
5-
5+ fn get_length ( s : & String ) -> usize {
6+ s. len ( )
7+ }
8+
9+ // Takes ownership - s1 is moved in and dropped here
10+ fn takes_ownership ( s : String ) {
11+ println ! ( "got ownership of: {}" , s) ;
12+ } // s is dropped here
13+
14+ // Borrows only - caller keeps ownership
15+ fn borrows_only ( s : & String ) {
16+ println ! ( "Just borrowing: {}" , s) ;
17+ }
18+
19+ fn main ( ) -> io:: Result < ( ) > {
20+ // PART 1 : Ownership and Moves
21+
22+ let s1 = String :: from ( "hello" ) ;
23+ let s2 = s1; // ownership moves to s2 & s1 is now invalid
24+
25+ println ! ( "s2 = {}" , s2) ;
26+
27+ // PART 2 : Copy Types -- NOTE : small types are copied not moved
28+
29+ let x = 5 ;
30+ let y = x;
31+ println ! ( "X = {}, y = {}" , x, y) ;
32+
33+ let is_active = true ;
34+ let also_active = is_active;
35+ println ! ( "is_active = {}, also_active = {}" , is_active, also_active) ;
36+
37+ // PART 3: Scope - values are dropped when owner leaves scope
38+
39+ {
40+ let s = String :: from ( "I only live here" ) ;
41+ println ! ( "inside scope: {}" , s) ;
42+ } ; // s is dropped here - memory freed automatically
43+
44+ // println!("s is not valid outside scope {}", s);
45+
46+ // PART 4: Borrowing with &
47+
48+ let s1 = String :: from ( "hello Universe" ) ;
49+ let length = get_length ( & s1) ; // lend s1 to the function - we keep ownership
50+ println ! ( "s1 = {}, length = {}" , s1, length) ;
51+
52+ // PART 5 : Immutable vs Mutable Borrows
53+
54+ // Multiple immutable borrows are fine
55+ let s = String :: from ( "hello" ) ;
56+ let r1 = & s;
57+ let r2 = & s;
58+ println ! ( "r1 = {}, r2 = {}" , r1, r2) ;
59+
60+ // One Mutable borrow - let's you change the value
61+ let mut s2 = String :: from ( "Universe" ) ;
62+ let r3 = & mut s2;
63+ r3. push_str ( " is big" ) ;
64+ println ! ( "r3 = {}" , r3) ;
65+
66+ /* NOTE : you CANNOT mix mutable & immutable borrows at the same time
67+ *
68+ * let r4 = &s2;
69+ * let r5 = &mut s2,
70+ * println!("{} {}", r4, r5);
71+ */
72+
73+ // PRAT 6 : Ownership through Functions
74+
75+ let s1 = String :: from ( "Lo Siento" ) ;
76+
77+ // Without borrowing -- ownership moves INTO the function and s1 is gone after
78+ takes_ownership ( s1) ;
79+ // println!("{}", s1); // printing s1 will show error
80+
81+ // With borrowing - we keep ownership
82+ let s2 = String :: from ( "Wilson" ) ;
83+ borrows_only ( & s2) ;
84+ println ! ( "s2 still valid : {}" , s2) ;
685 Ok ( ( ) )
7- }
86+ }
0 commit comments