blob: 5a8114ffe6cec179c5b974de5117097cb9faea84 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
// Compound types
//
// Types composed of another types
// String vs &str
// String - string slices
// String: heap allocated string type - NOT NULL TERMINATED
// (ptr, len, capacity)
// &str: immutable sequence of UTF-8 bytes in memory
// (ptr, len)
// &str - more lightweight and efficient
//
// String Literal: compile time known sequence of UTF-8 bytes
fn main() {
let s = String::from("Howdy partner");
let hello: &str = &s[0..5];
let world: &str = &s[6..13];
// Wow, suuuper safe
// let world: &str = &s[6..14];
println!("{} {}", hello, world);
compound();
string_playground();
concatenate();
}
fn compound() {
let s: Box<str> = "Howdy partner".into();
greetings(&s);
// We could also just not use a box here and create a slice.
// let s: &str = "Howdy partner";
// greetings(s);
}
fn greetings(s: &str) {
println!("{}", s);
}
fn string_playground() {
let mut s = String::from("");
s.push_str("hello, world");
s.push('!');
println!("Success");
}
fn concatenate() {
let s1: String = String::from("howdy,");
let s2: String = String::from("partner");
// you can concatenate a String + &str but you can't concatenate 2 Strings
// This consumes the string, and the ownership of s1 is transferred to s3
// This likely just push s2 into s1.
// Two ways of converting s2 to str:
// using .as_str() method
// let s3: String = s1 + s2.as_str();
// passing a reference to &s2
let s3: String = s1 + &s2;
println!("{}", s3);
}
|