@@ -92,9 +92,33 @@ fn foo(s: String) {
9292```
9393
9494If you have good reason. It's not polite to hold on to ownership you don't
95- need, and it can make your lifetimes more complex. Furthermore, you can pass
96- either kind of string into ` foo ` by using ` .as_slice() ` on any ` String ` you
97- need to pass in, so the ` &str ` version is more flexible.
95+ need, and it can make your lifetimes more complex.
96+
97+ ## Generic functions
98+
99+ To write a function that's generic over types of strings, use [ the ` Str `
100+ trait] ( http://doc.rust-lang.org/std/str/trait.Str.html ) :
101+
102+ ``` {rust}
103+ fn some_string_length<T: Str>(x: T) -> uint {
104+ x.as_slice().len()
105+ }
106+
107+ fn main() {
108+ let s = "Hello, world";
109+
110+ println!("{}", some_string_length(s));
111+
112+ let s = "Hello, world".to_string();
113+
114+ println!("{}", some_string_length(s));
115+ }
116+ ```
117+
118+ Both of these lines will print ` 12 ` .
119+
120+ The only method that the ` Str ` trait has is ` as_slice() ` , which gives you
121+ access to a ` &str ` value from the underlying string.
98122
99123## Comparisons
100124
@@ -134,7 +158,7 @@ println!("{}", s[0]);
134158
135159This does not compile. This is on purpose. In the world of UTF-8, direct
136160indexing is basically never what you want to do. The reason is that each
137- charater can be a variable number of bytes. This means that you have to iterate
161+ character can be a variable number of bytes. This means that you have to iterate
138162through the characters anyway, which is a O(n) operation.
139163
140164To iterate over a string, use the ` graphemes() ` method on ` &str ` :
@@ -147,14 +171,17 @@ for l in s.graphemes(true) {
147171}
148172```
149173
174+ Note that ` l ` has the type ` &str ` here, since a single grapheme can consist of
175+ multiple codepoints, so a ` char ` wouldn't be appropriate.
176+
150177This will print out each character in turn, as you'd expect: first "α", then
151178"ἰ", etc. You can see that this is different than just the individual bytes.
152179Here's a version that prints out each byte:
153180
154181``` {rust}
155182let s = "αἰθήρ";
156183
157- for l in s.as_bytes().iter () {
184+ for l in s.bytes () {
158185 println!("{}", l);
159186}
160187```
0 commit comments