1

I want to do this:

fn main() {
    let test = String::from("test");
    let vec = vec![&test];
    test(&vec[..]);
}

fn test (strs: &[&str]) {
    for s in strs {
        if s == "test" {
            println!("{}", s);
        }
    }
}

Is &[&std::string::String] different from &[&str]?

I know this answer, but it can't compare s == "test" because x.as_ref()'s type is T.

Kaoru
  • 33
  • 4
  • Can you explain more clearly why the answers to the question you linked are insufficient? The suggestion to use `>` works as well with `&String` as with `String`, and Matthieu M's answer also applies as well to explain why this isn't possible in general (although `String` and `&String` are different, the explanation in the answer still works because both are different than `&str`). – trent May 06 '21 at 21:00
  • I notice that in `main` you have a local variable named `test` which shadows the name of the function `test`. This causes an error when you make `fn test` generic but you can easily fix it by renaming either the variable or the function: [proof](https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=961490cdaae928ba73301d2afa14eecf) – trent May 06 '21 at 21:05
  • I forgot to add `as_ref()` and the answers I linked works fine. sorry and thank you for your comment. – Kaoru May 06 '21 at 21:14
  • No need to apologize! Duplicate questions can help future askers find the right answers, even when closed. – trent May 06 '21 at 21:24
  • 3
    A `String` is a triple of (pointer-to-data, length, capacity) and is three pointers wide (24 bytes on today's 64-bit architectures). A `&String` is a reference (pointer) to such triple and is just one pointer wide (8 bytes). A `&str` is a pair of (pointer-to-data, length), and is exactly two pointers wide (16 bytes). Even though `&String` and `&str` are similar in many ways, they have different representations in memory, from which it follows that you cannot cheaply "cast" a slice of one to a slice of the other. This is why everything from the `String`/`&str` answer applies here as well. – user4815162342 May 06 '21 at 21:36

0 Answers0