rust 如何为一个带范型的结构体实现Display特征?

语法问题。
已有代码

use std::fmt::Display;
use std::ops::Add;

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

impl<T: Add<Output = T>> Add for Point<T> {
    type Output = Point<T>;
    fn add(self, other_point: Point<T>) -> Point<T> {
        Point {
            x: self.x + other_point.x,
            y: self.y + other_point.y,
        }
    }
}

impl<T> Display for Point<T>{

}


fn main() {
    let a = Point { x: 1.0, y: 1.0 };

    let b = Point { x: 3.0, y: 4.0 };

    let c = a + b;

    println!("{:?}", c);
}

想请问下,impl Display for Point<T> 正确写法是啥样的?

阅读 2k
1 个回答
use std::fmt::{Display, Formatter, Result};
use std::ops::Add;

struct Point<T: Add<Output = T> + Display> {
    x: T,
    y: T,
}

impl<T: Add<Output = T> + Display> Add for Point<T> {
    type Output = Point<T>;
    fn add(self, other_point: Point<T>) -> Point<T> {
        Point {
            x: self.x + other_point.x,
            y: self.y + other_point.y,
        }
    }
}

impl<T: Display> Display for Point<T> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

fn main() {
    let a = Point { x: 1.0, y: 1.0 };
    let b = Point { x: 3.0, y: 4.0 };
    let c = a + b;

    println!("{}", c);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进