List contains not working with string literal variable

Hello, I'm getting started with learning Rust and I have a question about &str.

I have a list:

let available_toppings = ["mushroom", "pickle", "onion"];

on which I'm trying to run the contains method. This works when I use the string literal "olive" directly like:

if available_toppings.contains(&"olive")

but doesn't work when I declare a variable tfor &str and then use it in contains:

let requested_topping: &str = "olive"
if available_toppings.contains(requested_topping)

Can someone help me understand why the second example doesn't work ?

&"olive" has type &&str, but requested_topping has type &str.

Does that mean &"olive" is a reference to a string literal and not actually a string literal itself ?

Basically, yes. &"olive" (type &&str) is a reference to "olive". "olive" is a string literal (type &str) and technically a reference to the underlying buffer contains the characters (type str)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.