What brings together * in Rust?

I read books about in the section Stringand found that they used &*together to transform a piece of text. Here is what he says:

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.

In other words, they say that they convert Stringto &str. But why is this conversion made using both of the above attributes? Should this not be done in another way? Does &n't it mean that we take his link, then using *to track him down?

+4
source share
2 answers

In short : *triggers an explicit partition that can be overloaded through ops::Deref.


More details

Take a look at this code:

let s = "hi".to_string();  // : String
let a = &s;

a? &String! , String. , ?

let s = "hi".to_string();  // : String
let b = &*s;   // equivalent to `&(*s)`

b? &str! , ?

, *s. , * , *std::ops::Deref::deref(&s) ( , !). String :

impl Deref for String {
    type Target = str;
    fn deref(&self) -> &str { ... }
}

, *s *std::ops::Deref::deref(&s), deref() &str, . , *s str ( &).

str , , &str. , & ! , &str!


&*s - . , Deref -overload . , :

fn takes_string_slice(_: &str) {}

let s = "hi".to_string();  // : String
takes_string_slice(&s); // this works!
+9

&* (*), (&) . , .

Rust deref coercions. Deref DerefMut , !

String, , str, Vec<T>, [T], , Box<T>, T!

String:

String --deref--> str --ref--> &str

&, , *, ?

, . * & . , .

, &addr_string

( )

. . Rust? , , a &String , &str. , . :

let name: Option<String> = Some("Hello".to_string());
let name2: Option<&str> = name.as_ref().map(|s| &**s);

, :

&String -->deref--> String --deref--> str --ref--> &str

name.as_ref().map(String::as_str);

+8

Source: https://habr.com/ru/post/1664490/


All Articles