История изменений
Исправление Virtuos86, (текущая версия) :
Паста из первой редакции Книги:
Strings will coerce into
&strwith 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::connecthas a parameter of typeToSocketAddrs. A&stris okay but aStringmust 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
Stringas a&stris cheap, but converting the&strto aStringinvolves allocating memory. No reason to do that unless you have to!
Исходная версия Virtuos86, :
Паста из первой редакции Книги:
Strings will coerce into
&strwith 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::connecthas a parameter of typeToSocketAddrs. A&stris okay but aStringmust 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!