Use better wording
This commit is contained in:
parent
e7b4b0215f
commit
fb92015b07
|
@ -1,7 +1,7 @@
|
||||||
# 切片( Slice )
|
# 切片( Slice )
|
||||||
切片跟数组相似,但是切片的长度无法在编译期得知,因此你无法直接使用切片类型。
|
切片跟数组相似,但是切片的长度无法在编译期得知,因此你无法直接使用切片类型。
|
||||||
|
|
||||||
1. 🌟🌟 这里, `[i32]` 和 `str` 都是切片类型,但是直接使用它们会造成编译错误,如下代码所示。为了解决,你需要使用切片的引用: `&[i32]`, `&str`.
|
1. 🌟🌟 这里, `[i32]` 和 `str` 都是切片类型,但是直接使用它们会造成编译错误,如下代码所示。为了解决,你需要使用切片的引用: `&[i32]`,`&str`。
|
||||||
```rust,editable
|
```rust,editable
|
||||||
|
|
||||||
// 修复代码中的错误,不要新增代码行!
|
// 修复代码中的错误,不要新增代码行!
|
||||||
|
@ -76,17 +76,17 @@ fn main() {
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut s = String::from("hello world");
|
let mut s = String::from("hello world");
|
||||||
|
|
||||||
// 这里, &s 是 `&String` 类型,但是 `first_word` 函数需要的是 `&str` 类型。
|
// 这里, &s 是 `&String` 类型,但是 `first_character` 函数需要的是 `&str` 类型。
|
||||||
// 尽管两个类型不一样,但是代码仍然可以工作,原因是 `&String` 会被隐式地转换成 `&str` 类型,如果大家想要知道更多,可以看看 Deref 章节: https://course.rs/advance/smart-pointer/deref.html
|
// 尽管两个类型不一样,但是代码仍然可以工作,原因是 `&String` 会被隐式地转换成 `&str` 类型,如果大家想要知道更多,可以看看 Deref 章节: https://course.rs/advance/smart-pointer/deref.html
|
||||||
let word = first_word(&s);
|
let ch = first_character(&s);
|
||||||
|
|
||||||
s.clear(); // error!
|
s.clear(); // error!
|
||||||
|
|
||||||
println!("the first word is: {}", word);
|
println!("the first character is: {}", ch);
|
||||||
}
|
}
|
||||||
fn first_word(s: &str) -> &str {
|
fn first_character(s: &str) -> &str {
|
||||||
&s[..1]
|
&s[..1]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/slice.md)找到答案(在 solutions 路径下)
|
> 你可以在[这里](https://github.com/sunface/rust-by-practice/blob/master/solutions/compound-types/slice.md)找到答案(在 solutions 路径下)
|
||||||
|
|
Loading…
Reference in New Issue