在Rust中为特定类型实现结构体的函数

在下面的代码中,我试图实现一个通用结构。我想要实现的是,对于类型为 String 的 T,打印self.x值,对于所有其他类型,同时打印self.xself.y

这个问题与 无关trait,我只是尝试impl为结构函数。

use core::fmt::Display;
use core::fmt::Debug;

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T
}

impl Point<String> {
    fn print(&self) {
        println!("{:?}", self.x);
    }
}

impl<T: Display + Debug> Point<T> {
    fn print(&self) {
        println!("{:?}", self.x);
        println!("{:?}", self.y);
    }
}

fn main() {
    let x = Point{x: String::from("123"), y: String::from("456")};
    let y = Point{x: 123, y: 456};
    //let z = Point{x: vec![1,2,3], y: vec![4,5,6]};
    
    x.print();
    y.print();
    //z.print();
}

但是,我收到以下编译错误:

error[E0592]: duplicate definitions with name `print`

实现它的正确方法是什么?

此外,我还尝试将向量用作 x 和 y(z主中的),这是不允许的,我想知道原因。

回答

Rust 尚不支持专业化,但同样存在跟踪问题。但是您的要求可以通过检查来满足TypeId

fn is_string<T: Any>() -> bool {
    TypeId::of::<String>() == TypeId::of::<T>()
}

impl<T: Debug + Any> Point<T> {
    fn print(&self) {
        if is_string::<T>() {
            println!("{:?}", self.x);
        } else {
            println!("{:?}", self.x);
            println!("{:?}", self.y);
        }
    }
}

操场

此代码也适用于向量。在您的代码中,您添加了一个Display未由Vec.

  • Just note that you have to be careful with this because `TypeId::of` is very literal, so `is_string()` will return true only for actual `String`, not for e.g. `&'static str`. Also, it won't work for any `T` that contains a non-static lifetime (there was a suggestion to change this, but it got [rejected](https://github.com/rust-lang/rust/issues/41875)).

以上是在Rust中为特定类型实现结构体的函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>