mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 04:29:41 +00:00
Merge pull request #486 from Hugoo/master
Rename first_word to first_letter
This commit is contained in:
@ -84,15 +84,15 @@ fn main() {
|
|||||||
fn main() {
|
fn main() {
|
||||||
let mut s = String::from("hello world");
|
let mut s = String::from("hello world");
|
||||||
|
|
||||||
// Here, &s is `&String` type, but `first_word` need a `&str` type.
|
// Here, &s is `&String` type, but `first_letter` needs a `&str` type.
|
||||||
// It works because `&String` can be implicitly converted to `&str. If you want to know more, this is called `Deref coercion`.
|
// It works because `&String` can be implicitly converted to `&str. If you want to know more, this is called `Deref coercion`.
|
||||||
let word = first_word(&s);
|
let letter = first_letter(&s);
|
||||||
|
|
||||||
s.clear(); // error!
|
s.clear(); // error!
|
||||||
|
|
||||||
println!("the first word is: {}", word);
|
println!("the first letter is: {}", letter);
|
||||||
}
|
}
|
||||||
fn first_word(s: &str) -> &str {
|
fn first_letter(s: &str) -> &str {
|
||||||
&s[..1]
|
&s[..1]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -62,16 +62,16 @@ fn main() {
|
|||||||
fn main() {
|
fn main() {
|
||||||
let mut s = String::from("hello world");
|
let mut s = String::from("hello world");
|
||||||
|
|
||||||
// here, &s is `&String` type, but `first_word` need a `&str` type.
|
// here, &s is `&String` type, but `first_letter` needs a `&str` type.
|
||||||
// it works because `&String` can be implicitly converted to `&str, If you want know more ,this is called `Deref`
|
// it works because `&String` can be implicitly converted to `&str, If you want know more ,this is called `Deref`
|
||||||
let word = first_word(&s);
|
let letter = first_letter(&s);
|
||||||
|
|
||||||
println!("the first word is: {}", word);
|
println!("the first letter is: {}", letter);
|
||||||
|
|
||||||
s.clear();
|
s.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn first_word(s: &str) -> &str {
|
fn first_letter(s: &str) -> &str {
|
||||||
&s[..1]
|
&s[..1]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user