【问题标题】:trait constraint on specific function rather than whole implementation对特定功能而不是整个实现的特征约束
【发布时间】:2014-12-12 17:36:02
【问题描述】:

我正在尝试实现一个可以接受任何类型参数的通用结构。

struct Position<T>{
    x: T,
    y: T,
}

impl<T:Num> Position<T>{
    fn add(&self, other: &Position<T>) -> Box<Position<T>>{
        box Position{x:self.x + other.x, y:self.y + other.y}
    }

    fn display(&self) -> String{
        "WELCOME ".to_string()
    }
}

现在我可以定义了

let original_position = Position::<int>{x: 2, y:23};
let another_postion   = original_position.add(&original_position);
let welcome           = original_postion.display();

没有任何错误

同样,我可以执行以下操作而不会出现任何错误。

let string_position = Position::<String>{x: "x_pos".to_string(), y: "y_pos".to_string()};

现在由于 Num 特征约束,我无法调用以下内容(这很明显)。

string_position.add(&original_position);

但是,我的问题是,由于相同的 Num 特征约束,现在我无法调用以下命令

string_position.display()

上述函数与Num类型无关,它只是返回字符串“WELCOME”

我需要如何重写实现,以便 add 方法只能由 Position&lt;Num&gt; 调用,而 display 可以由任何其他通用实现调用。

【问题讨论】:

    标签: rust traits generic-function


    【解决方案1】:

    您应该创建单独的实现,一个有绑定,另一个没有,如下所示:

    impl<T:Num> Position<T>{
        fn add(&self, other: &Position<T>) -> Box<Position<T>>{
            box Position{x:self.x + other.x, y:self.y + other.y}
        }
    }
    
    impl<T> Position<T>{
        fn display(&self) -> String{
            "WELCOME ".to_string()
        }
    }
    

    您可以看到它有效here

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多