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

Har*_*hao 2 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();
}
Run Code Online (Sandbox Code Playgroud)

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

error[E0592]: duplicate definitions with name `print`
Run Code Online (Sandbox Code Playgroud)

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

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

Mih*_*hir 5

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

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

  • 请注意,您必须小心这一点,因为“TypeId::of”非常字面意思,因此“is_string()”仅对实际的“String”返回 true,而不是对“&amp;'static str”等返回 true。另外,它不适用于任何包含非静态生命周期的“T”(有人建议更改此设置,但它被[拒绝](https://github.com/rust-lang/rust/issues /41875))。 (3认同)