История изменений
Исправление Virtuos86, (текущая версия) :
Паста из первой редакции Книги:
Strings will coerce into
&str
with an&
:fn takes_slice(slice: &str) { println!("Got: {}", slice); } fn main() { let s = "Hello".to_string(); takes_slice(&s); }
This coercion does not happen for functions that accept one of
&str
’s traits instead of&str
. For example,TcpStream::connect
has a parameter of typeToSocketAddrs
. A&str
is okay but aString
must be explicitly converted using&*
.use std::net::TcpStream; TcpStream::connect("192.168.0.1:3000"); // Parameter is of type &str. let addr_string = "192.168.0.1:3000".to_string(); TcpStream::connect(&*addr_string); // Convert `addr_string` to &str.
Viewing a
String
as a&str
is cheap, but converting the&str
to aString
involves allocating memory. No reason to do that unless you have to!
Исходная версия Virtuos86, :
Паста из первой редакции Книги:
Strings will coerce into
&str
with an&
:fn takes_slice(slice: &str) { println!("Got: {}", slice); } fn main() { let s = "Hello".to_string(); takes_slice(&s); }
This coercion does not happen for functions that accept one of
&str
’s traits instead of&str
. For example,TcpStream::connect
has a parameter of typeToSocketAddrs
. A&str
is okay but aString
must be explicitly converted using&*
.use std::net::TcpStream; TcpStream::connect("192.168.0.1:3000"); // Parameter is of type &str. let addr_string = "192.168.0.1:3000".to_string(); TcpStream::connect(&*addr_string); // Convert `addr_string` to &str.
Viewing a String as a &str is cheap, but converting the &str to a String involves allocating memory. No reason to do that unless you have to!