Skip to content
Permalink
Browse files
fix generics section
  • Loading branch information
steveklabnik committed Sep 22, 2014
1 parent ed63fd5 commit c6b3569bc7afae1e9b5567dceb51fafc52c9d7e6
Showing 1 changed file with 27 additions and 7 deletions.
@@ -96,12 +96,14 @@ need, and it can make your lifetimes more complex.
## Generic functions
To write a function that's generic over types of strings, use [the `Str`
trait](http://doc.rust-lang.org/std/str/trait.Str.html):
To write a function that's generic over types of strings, you have two options:
`&str`, or using [the `Str`
trait](http://doc.rust-lang.org/std/str/trait.Str.html). Most of the time, you
should prefer just taking `&str`:
```{rust}
fn some_string_length<T: Str>(x: T) -> uint {
x.as_slice().len()
fn some_string_length(x: &str) -> uint {
x.len()
}
fn main() {
@@ -111,14 +113,32 @@ fn main() {
let s = "Hello, world".to_string();
println!("{}", some_string_length(s));
println!("{}", some_string_length(s.as_slice()));
}
```
Both of these lines will print `12`.
The only method that the `Str` trait has is `as_slice()`, which gives you
access to a `&str` value from the underlying string.
If you're using some kind of nested structure that has strings inside and you
wish to be generic, you should use `Str`:
```{rust}
fn sum_of_string_length<T: Str>(xs: &[T]) -> uint {
xs.iter().fold(0, |acc, x| acc + x.as_slice().len())
}
fn main() {
let s = "Hello, world";
println!("{}", sum_of_string_length([s]));
let s = "Hello, world".to_string();
println!("{}", sum_of_string_length([s]));
}
```
This is prefereable because it can save you allocating copies of what's inside.
## Comparisons

0 comments on commit c6b3569

Please sign in to comment.