除了特征之外,还有其他方法可以向我不拥有的类型添加方法吗? [英] Is there a way other than traits to add methods to a type I don't own?

查看:54
本文介绍了除了特征之外,还有其他方法可以向我不拥有的类型添加方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展 Grid 来自活塞 2dgraphics 库的结构.没有方法可以获取特定单元格窗口上的位置,因此我实现了一个特征来为我计算.然后,我想要一种方法来计算网格上特定单元格的邻居,因此我实现了另一个特征.

I'm trying to extend the Grid struct from the piston-2dgraphics library. There's no method for getting the location on the window of a particular cell, so I implemented a trait to calculate that for me. Then, I wanted a method to calculate the neighbours of a particular cell on the grid, so I implemented another trait.

关于这件事的一些事情很丑陋,感觉没有必要,因为除了这个特定的网格结构之外,我可能永远不会将这些特征用于任何其他事物.Rust 中是否有另一种方法来扩展类型而不必每次都实现 trait?

Something about this is ugly and feels unnecessary seeing as how I'll likely never use these traits for anything other than this specific grid structure. Is there another way in Rust to extend a type without having to implement traits each time?

推荐答案

从 Rust 1.27 开始,没有其他方法.不可能在另一个板条箱中定义的类型上定义固有方法.

As of Rust 1.27, no, there is no other way. It's not possible to define inherent methods on a type defined in another crate.

您可以使用所需的方法定义自己的特征,然后为外部类型实现该特征.这种模式被称为扩展特征.按照惯例,扩展 trait 的名称以 Ext 结尾,以表明此 trait 不打算用作通用绑定或 trait 对象.标准库中有几个例子.>

You can define your own trait with the methods you need, then implement that trait for an external type. This pattern is known as extension traits. The name of extension traits, by convention, ends with Ext, to indicate that this trait is not meant to be used as a generic bound or as a trait object. There are a few examples in the standard library.

trait DoubleExt {
    fn double(&self) -> Self;
}

impl DoubleExt for i32 {
    fn double(&self) -> Self {
        *self * 2
    }
}

fn main() {
    let a = 42;
    println!("{}", 42.double());
}

其他库也可以导出扩展特征(例如:byteorder).但是,对于任何其他 trait,您需要使用 use SomethingExt; 将 trait 的方法引入范围.

Other libraries can also export extension traits (example: byteorder). However, as for any other trait, you need to bring the trait's methods in scope with use SomethingExt;.

这篇关于除了特征之外,还有其他方法可以向我不拥有的类型添加方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆