Is `s.as_str() the same as `&s[..]`?

This entry: String in std::string - Rust has the following example:

let s = String::from("foo");

assert_eq!("foo", s.as_str());

Is s.as_str() the same as &s[..] ? If not, what's the difference?

Assuming that s is a String, then yes, they are the same.

1 Like

Both s.as_str() and &s[..] give you a reference to the string slice of the String s. They are equivalent in functionality and provide the same result.

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.