Slices and functions
- Rust course
- Beginner
- Lesson 57/115
- 4 min
Pass slices to functions to borrow data.
Slices and functions
Taking &str instead of &String, and &[T] instead of &Vec<T>, lets a function accept Strings, literals and sub-slices alike. The returned slice is a part of the input:
fn ilk_kelime(s: &str) -> &str {
for (i, b) in s.bytes().enumerate() {
if b == b' ' {
return &s[..i];
}
}
&s[..]
}As long as the returned &str borrows s, the source can't be changed.
Built-in helpers
The standard library offers methods that produce slices without hand-written loops:
let s = "ad soyad yaş";
let ilk = s.split(' ').next().unwrap_or(""); // "ad"
let (sol, sag) = s.split_at(2); // ("ad", " soyad yaş")
let temiz = " rust ".trim(); // "rust"split_whitespace, lines and trim all return parts of the source as &str without copying.
Practice First word
Write fn ilk_kelime(s: &str) -> &str: find the first space with bytes().enumerate() and return &s[..i]; if there is no space, &s[..]. Print the results for "merhaba dünya" and "tek" separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn ilk_kelime(s: &str) -> &str {
for (i, b) in s.bytes().enumerate() {
if b == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
println!("{} {}", ilk_kelime("merhaba dünya"), ilk_kelime("tek"));
}Expected output
merhaba tek
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is <code>ilk_kelime</code> called with a <code>String</code>?
- ilk_kelime(metin)
- ilk_kelime(*metin)
- It can't be called
- ilk_kelime(&metin) Correct answer
Explanation: &String is converted to &str automatically (deref coercion).
2 Slice parameter
fn en_buyuk(v: ____) -> i32 {
*v.iter().max().unwrap()
}
fn en_buyuk(v: &[i32]) -> i32 {
*v.iter().max().unwrap()
}
Explanation: &[i32] accepts both vector and array references.
3 Method and result on " ad soyad "
| Term | Meaning |
|---|---|
trim() |
"ad soyad" |
split_whitespace().count() |
2 |
len() |
11 |
trim().split_at(2).0 |
"ad" |