Browse Source

Slice Type

master
Saura Sambit 11 months ago
parent
commit
d215a19b31
2 changed files with 35 additions and 11 deletions
  1. +23
    -0
      README.md
  2. +12
    -11
      ch04/ownership/src/main.rs

+ 23
- 0
README.md View File

@@ -262,3 +262,26 @@ The benefit of having this restriction is that Rust can prevent data races at co

######Dangling References
In Rust, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.
######The Slice Type
`slice` does not have ownership. It lets you reference a contiguous sequence of elements in a collection rather than the whole collection.

A `string slice` is a reference to a part of a `String`:
```
let s = String::from("hello world");
let hello = &s[0..5]; //hello
let world = &s[6..11]; // world
```
Write a function that takes a string and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned:
```
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[..]
}
```

+ 12
- 11
ch04/ownership/src/main.rs View File

@@ -1,23 +1,24 @@
fn main() {
let s = String::from("hello"); // s comes into scope
let s = String::from("hello"); // s comes into scope

takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here

let x = 5; // x comes into scope

makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward
let x = 5; // x comes into scope

makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward
} // Here, x goes out of scope, then s. But because s's value was moved, nothing
// special happens.

fn takes_ownership(some_string: String) { // some_string comes into scope
fn takes_ownership(some_string: String) {
// some_string comes into scope
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.

fn makes_copy(some_integer: i32) { // some_integer comes into scope
fn makes_copy(some_integer: i32) {
// some_integer comes into scope
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
} // Here, some_integer goes out of scope. Nothing special happens.

Loading…
Cancel
Save