mirror of
https://github.com/rust-lang/rust.git
synced 2025-01-01 18:35:25 +00:00
rollup merge of #21780: steveklabnik/no_as_slice
Use auto deref instead.
This commit is contained in:
commit
a75e308a61
@ -3518,7 +3518,7 @@ An example of each kind:
|
||||
```{rust}
|
||||
let vec: Vec<i32> = vec![1, 2, 3];
|
||||
let arr: [i32; 3] = [1, 2, 3];
|
||||
let s: &[i32] = vec.as_slice();
|
||||
let s: &[i32] = &vec;
|
||||
```
|
||||
|
||||
As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The
|
||||
|
@ -100,7 +100,7 @@ To write a function that's generic over types of strings, use `&str`.
|
||||
|
||||
```
|
||||
fn some_string_length(x: &str) -> uint {
|
||||
x.len()
|
||||
x.len()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@ -110,7 +110,7 @@ fn main() {
|
||||
|
||||
let s = "Hello, world".to_string();
|
||||
|
||||
println!("{}", some_string_length(s.as_slice()));
|
||||
println!("{}", some_string_length(&s));
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -174,13 +174,13 @@ match origin {
|
||||
}
|
||||
```
|
||||
|
||||
If you want to match against a slice or array, you can use `[]`:
|
||||
If you want to match against a slice or array, you can use `&`:
|
||||
|
||||
```{rust}
|
||||
fn main() {
|
||||
let v = vec!["match_this", "1"];
|
||||
|
||||
match v.as_slice() {
|
||||
match &v {
|
||||
["match_this", second] => println!("The second element is {}", second),
|
||||
_ => {},
|
||||
}
|
||||
|
@ -82,7 +82,7 @@ fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
|
||||
}
|
||||
};
|
||||
|
||||
let mut text = text.as_slice();
|
||||
let mut text = &text;
|
||||
let mut total = 0;
|
||||
while !text.is_empty() {
|
||||
match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
|
||||
|
@ -36,36 +36,16 @@ s.push_str(", world.");
|
||||
println!("{}", s);
|
||||
```
|
||||
|
||||
You can get a `&str` view into a `String` with the `as_slice()` method:
|
||||
`String`s will coerece into `&str` with an `&`:
|
||||
|
||||
```{rust}
|
||||
```
|
||||
fn takes_slice(slice: &str) {
|
||||
println!("Got: {}", slice);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let s = "Hello".to_string();
|
||||
takes_slice(s.as_slice());
|
||||
}
|
||||
```
|
||||
|
||||
To compare a String to a constant string, prefer `as_slice()`...
|
||||
|
||||
```{rust}
|
||||
fn compare(string: String) {
|
||||
if string.as_slice() == "Hello" {
|
||||
println!("yes");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
... over `to_string()`:
|
||||
|
||||
```{rust}
|
||||
fn compare(string: String) {
|
||||
if string == "Hello".to_string() {
|
||||
println!("yes");
|
||||
}
|
||||
takes_slice(&s);
|
||||
}
|
||||
```
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user