@@ -988,7 +988,7 @@ We **do not** copy the data on the heap that the pointer refers to.
988
988
---
989
989
990
990
``` rust
991
- let s1 = String : from (" Hello" );
991
+ let s1 = String :: from (" Hello" );
992
992
let s2 = s1 ;
993
993
994
994
println! (" {}, world!" , s1 );
@@ -1505,22 +1505,25 @@ If you attempt to create a string slice in the middle of a multi-byte character,
1505
1505
your program will exit with an error.
1506
1506
1507
1507
``` rust
1508
- fn first_word (s : & String ) -> usize {
1508
+ let greeting = " Hello, \ u{ 1F30D} !" ; // The globe emoji is a multi-byte character
1509
+ let sliced = & greeting [0 .. 9 ]; // Panics because it's slicing through it
1510
+ ```
1511
+
1512
+ ---
1513
+
1514
+ ``` rust
1515
+ fn first_word (s : & String ) -> & str {
1509
1516
let bytes = s . as_bytes ();
1510
1517
1511
1518
for (i , & item ) in bytes . iter (). enumerate () {
1512
1519
if item == b ' ' {
1513
- return i ;
1520
+ return & s [ 0 .. i ] ;
1514
1521
}
1515
1522
}
1516
1523
1517
- s . len ()
1524
+ & s [ .. ]
1518
1525
}
1519
- ```
1520
-
1521
- ---
1522
1526
1523
- ``` rust
1524
1527
fn main () {
1525
1528
let mut s = String :: from (" Hello world" );
1526
1529
let word = first_word (& s );
@@ -1539,12 +1542,14 @@ Compile-time error!
1539
1542
1540
1543
If we have an immutable reference to something,
1541
1544
we cannot also take a mutable reference.
1542
- Because clear needs to truncate the ` String ` ,
1545
+
1546
+ Because ` clear() ` needs to truncate the ` String ` ,
1543
1547
it needs to get a mutable reference.
1544
- The ` println! ` after the call to clear uses the reference in word,
1548
+ The ` println! ` after the call to ` clear() ` uses the reference in ` word ` ,
1545
1549
so the immutable reference must still be active at that point.
1546
- Rust disallows the mutable reference in clear and the immutable
1547
- reference in word from existing at the same time, and compilation fails.
1550
+ Rust disallows the mutable reference in ` clear() ` and the immutable
1551
+ reference in ` word ` from existing at the same time, and compilation fails.
1552
+
1548
1553
Not only has Rust made our API easier to use,
1549
1554
but it has also eliminated an entire class of errors at compile time!
1550
1555
0 commit comments