# Two very different String methods for the same job?

**URL:** <https://internals.rust-lang.org/t/two-very-different-string-methods-for-the-same-job/23763>\
**Category:** libs\
**Created:** [November 23, 2025, 4:55pm UTC](https://internals.rust-lang.org/t/two-very-different-string-methods-for-the-same-job/23763 "2025-11-23T16:55:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dwarsloeper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dwarsloeper/32/11073_2.png) [@Dwarsloeper](https://internals.rust-lang.org/u/Dwarsloeper)\
**Post date:** [November 23, 2025, 4:55pm UTC](https://internals.rust-lang.org/t/two-very-different-string-methods-for-the-same-job/23763/1 "2025-11-23T16:55:32Z")

</div>

Afaict, these inline and optimize to identical asm. Is there some compiler-stdlib magic whereby the 2nd taps into the 1st?

Or: The 2nd suggests that the 3 `String` usizes are optimized to be such that their first 2 can dual-purpose also serve as an `str` fat pointer. But then, why not do the same in the 1st case? That would at least elimitate an `unsafe’.

```rust
pub const fn as_str(&self) -> &str {
    // SAFETY: String contents are stipulated to be valid UTF-8, invalid contents are an error
    // at construction.
    unsafe { str::from_utf8_unchecked(self.vec.as_slice()) }
}

impl AsRef<str> for String {
    #[inline]
    fn as_ref(&self) -> &str {
        self
    }
}

```

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [November 23, 2025, 5:06pm UTC](https://internals.rust-lang.org/t/two-very-different-string-methods-for-the-same-job/23763/2 "2025-11-23T17:06:31Z")

</div>

The compiler–stdlib magic [(deref coercion)](https://doc.rust-lang.org/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods) happens in `as_ref` which implicitly calls the [`Deref` impl](https://doc.rust-lang.org/src/alloc/string.rs.html#2723). As such, all of `&string`, `string.as_ref()`, and `string.as_str()` end up executing the same code.
