rust - 为什么可以在 String 上调用 Colorize trait 方法,而 Strin

来自 Colorize 特征 doc , String 不暗示它(而 &str 暗示它)。

fn blue(self) -> ColoredString
where
    Self: Sized, 

但是为什么String类型可以调用它的方法呢?

use colored::Colorize;

fn main() {
    let blue = "blue".to_owned().blue();
    println!("{}", blue);
}


编辑

  • [未解决] 我该如何脱糖? (具体来说,找出自动取消引用正在发生)

  • 幕后发生了什么?

方法调用的类型强制。 String 可以通过 &*String

强制转换为 &str

最佳答案

性状 Colorize&'a str 实现, 和 String工具 Deref<Target=str> .

Rust 方法调用规则意味着该值可能会自动借用或取消引用。

这意味着我们的方法调用 String , Rust 将寻找一些具有以下类型之一的方法作为接收者类型

  • String
  • &String
  • &mut String
  • str (通过取消引用)
  • &str (这个让方法调用起作用)
  • &mut str

String只是借用,调用.blue()后即可使用

use colored::Colorize;

fn main() {
    let x = "hello".to_string();
    let y = x.blue();

    println!("{}", x);
    println!("{}", y);
}

link to rust reference regarding how method calls are resolved

关于rust - 为什么可以在 String 上调用 Colorize trait 方法,而 String 不实现 Colorize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69082202/

相关文章:

swiftui - PresentationMode 触发器 "Variable X used be

snowflake-cloud-data-platform - 使用 Google 作为身份提供商

go - 在 golang 中将 []*string 转换为 []string

ruby-on-rails - Rubocop 在 Rails 中的蓝图序列化程序自定义字段中警告

c++ - 如何区分ascii值和数字?

javascript - JS : proper way of using optional cha

python - 您如何为加权平均平均值迭代地为数据框列赋予权重?

node.js - 如何在 nodejs 中使用 getRandomValues()?

git - 如何创建自定义 git/bash 脚本?

javascript - $(this) 在我的 jQuery 点击函数中不起作用