You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查询Rust中&str类型的Display trait实现位置

查找&str的Display trait实现线索
  • &str并没有单独的Display trait实现,它的Display能力来自Rust标准库的blanket实现(通用覆盖实现):标准库为所有实现了Display的类型的引用(&T)自动实现了Display,这个逻辑在std::fmt模块中。

  • 对应的源码在std/src/fmt/mod.rs里,核心代码如下:

impl<T: Display + ?Sized> Display for &T {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        Display::fmt(&**self, f)
    }
}

因为str本身已经实现了Display,所以&str会自动匹配这个通用实现,调用时直接转发到内部str的Display逻辑。

  • 你之前没找到是因为没关注到这个通用实现,去fmt/mod.rs里搜索impl<T: Display就能定位到这段代码。另外还有针对&mut T的类似通用实现,逻辑完全一致。

内容的提问来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:06:20