pub fn ownership() {
let mut s1 = String::from("hello");
s1.push_str(" world!");
println!("{}", s1);
{
let s2 = String::from("hello");
}
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
let s1 = String::from("hello");
let s2 = s1;
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
}
pub fn ownership_function() {
let s = String::from("hello");
takes_ownership(s);
let x = 5;
makes_copy(x);
println!("{}", x);
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
}
fn ownership_return() {
let s1 = gives_ownership();
let s2 = String::from("world");
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
pub fn ownership_reference() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
pub fn ownership_mutable_reference() {
let mut s = String::from("hello");
println!("{}", s);
change(&mut s);
println!("{}", s);
let r3 = &s;
let r4 = &s;
println!("{} {}", r3, r4);
let r5 = &mut s;
println!("{}", r5);
}
fn change(s: &mut String) {
s.push_str(", world")
}
pub fn ownership_dangling_reference() {
let reference_to_nothing = dangle();
}
fn dangle() -> String { let s = String::from("hello"); s }
pub fn owner_slice() {
let mut s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
let hello = &s[..5];
let world = &s[6..];
let whole = &s[..];
println!("{} {} {} {}", hello, world, whole, s);
let res = first_world(&s);
println!("{}", res); s.clear();
}
fn first_world(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}