Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: How does a reference to a String become a string slice?

Tags:

rust

I'm trying to understand the concept of strings and string slices.

fn say_hello_slice(slice: &str) {
    println!("Hey {}", slice);
}

fn say_hello_string(string: &String) {
    println!("{:?}", string);
}

fn print_int(int_ref: &i32) {
    println!("{:?}", int_ref);
}

fn main() {
    let slice: &str = "you";
    let s: String = String::from("String");
    say_hello_slice(slice);
    say_hello_slice(&s);

    let number: i32 = 12345;
    print_int(&number);

    say_hello_string(&s);
}

This program gives the below output when I compile and run:

Hey you
Hey String
12345
"String"

I understand that when & is added to the binding it becomes a reference to its binding type. For example, & to number in above program becomes &i32.

I don't understand how it works when I add & to String and it becomes &str.

like image 292
Rajkumar Natarajan Avatar asked Mar 16 '18 07:03

Rajkumar Natarajan


People also ask

What is a string slice rust?

A string slice is a reference to part of a String , and it looks like this: let s = String::from("hello world"); let hello = &s[0.. 5]; let world = &s[6.. 11]; Rather than a reference to the entire String , hello is a reference to a portion of the String , specified in the extra [0..

How do you cut string in Rust?

In Rust, we can use the trim() method of a string to remove the whitespace characters around that string. This method removes the leading and trailing whitespace characters of a given string.

What is the difference between string and STR in Rust?

String is the dynamic heap string type, like Vec : use it when you need to own or modify your string data. str is an immutable1 sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer.

What is slicing in Rust?

A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime.


1 Answers

You have just witnessed the Deref trait. This trait has three uses:

  • Conversion to another type when dereferencing (the * operator)
  • Automatic conversion if necessary (coercion) when borrowing
  • You can call methods of another type directly.

In your case, because String implements Deref<Target = str> this means that &s is coerced into a &str.

More info here.

like image 120
Minijackson Avatar answered Sep 21 '22 14:09

Minijackson