【问题标题】:call trait method when struct method has same name当 struct 方法具有相同名称时调用 trait 方法
【发布时间】:2022-10-06 05:49:25
【问题描述】:

在以下代码中:

pub trait Thinger {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("trait method: {:?}", self);
    }
}

#[derive(Debug)]
pub struct Thing(f64);

impl Thing {
    fn print_thing(&self) where Self: core::fmt::Debug {
        println!("method: {:?}", self);
    }
}

impl Thinger for Thing {}

fn main() {
    let thing = Thing(3.14);
    thing.print_thing();
}

如何调用Thinger 的print_thing 方法?
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0717f5615e10e3a1349f6db9cb9c3306

我在 The Book 中看到过,但我在任何地方都找不到。

【问题讨论】:

    标签: rust overriding traits


    【解决方案1】:
    Thinger::print_thing(&thing)
    
    <Thing as Thinger>::print_thing(&thing)
    

    这是您一直指的The Book 的片段。

    【讨论】:

    • 我要补充一点,这称为通用函数调用语法。
    【解决方案2】:

    Aleksander Krauze 做到了,但为了完整性,还有另一种方法:
    https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4450b905f10198967090c8f56e3acfeb

    Thinger::print_thing(&amp;thing);

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 2013-06-14
      相关资源
      最近更新 更多