mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:41:18 -06:00
Make calculate_length more idiomatic. Fixes #76.
This commit is contained in:
@@ -21,9 +21,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn calculate_length(s: &String) -> usize {
|
fn calculate_length(s: &String) -> usize {
|
||||||
let length = s.len();
|
s.len()
|
||||||
|
|
||||||
length
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -43,9 +41,7 @@ Let’s take a closer look at the function call here:
|
|||||||
|
|
||||||
```rust
|
```rust
|
||||||
# fn calculate_length(s: &String) -> usize {
|
# fn calculate_length(s: &String) -> usize {
|
||||||
# let length = s.len();
|
# s.len()
|
||||||
#
|
|
||||||
# length
|
|
||||||
# }
|
# }
|
||||||
let s1 = String::from("hello");
|
let s1 = String::from("hello");
|
||||||
|
|
||||||
@@ -61,9 +57,7 @@ a reference as an argument. Let’s add some explanatory annotations:
|
|||||||
|
|
||||||
```rust
|
```rust
|
||||||
fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
||||||
let length = s.len();
|
s.len()
|
||||||
|
|
||||||
length
|
|
||||||
} // Here, s goes out of scope. But since it does not have ownership of what
|
} // Here, s goes out of scope. But since it does not have ownership of what
|
||||||
// it refers to, nothing happens.
|
// it refers to, nothing happens.
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user