Rust
RUST Documentation 따라 공부하기 8
2019.12.30
The Slice Type
Another data type that does not have ownership is the slice.
- String 속 첫 단어 출력하기
fn first_word(s: $string) -> usize {
let bytes = s.as_bytes(); // convert `String` to an array of bytes.
for (i, &item) in bytes.iter().enumerate() {
// `iter` is a method that returns each element in a collection
// `enumerate` wraps the result of `iter` and returns each element as part of a tuple instead : (index, reference) .
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // empties the String -> making it to ""
// but word is still 5 -> it whould be a bug.
}
Function
first_word
returns the index of the end of the first word in the string.But, it's only a meaningful number in the context of the
&String
.
Solution : String Slices
let s = String::from("hello world");
let hello = &s[0..5]; // &s[..5];
let workd = &s[6..11]; // &s[6..];
// &s[..]; is possible
- make
first_word
function to return slice
// let s = "Hello, world!";
// type of s : &str, &str is an immutable reference.
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item ==b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error : s is borrowed!
}
- better code:
fn first_word(s: &str) -> &str {
let bytes=s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item==b' '{
return &s[..i];
}
}
&s[..]
}
fn main() {
let my_string = String::from("hello world");
let word = first_word(&my_string[..]);
// String type -> make it to string slice.
// more general code.
}
Other Slices
let a = [1,2,3,4,5];
let slice = &a[1..3]; // type of slice : &[i32]