应该在 struct 和 impl 中复制特征边界吗? [英] Should trait bounds be duplicated in struct and impl?

查看:24
本文介绍了应该在 struct 和 impl 中复制特征边界吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用具有泛型类型的结构.虽然它的实现只对给定的 trait bound 有效,但结构体可以定义为有或没有相同的边界.该结构体的字段是私有的,因此无论如何其他代码都无法创建实例.

The following code uses a struct with generic type. While its implementation is only valid for the given trait bound, the struct can be defined with or without the same bound. The struct's fields are private so no other code could create an instance anyway.

trait Trait {
    fn foo(&self);
}

struct Object<T: Trait> {
    value: T,
}

impl<T: Trait> Object<T> {
    fn bar(object: Object<T>) {
        object.value.foo();
    }
}

应该省略结构的特征绑定以符合 DRY 原则,还是应该给出它来澄清依赖关系?或者在某些情况下应该优先考虑一种解决方案吗?

Should the trait bound for the structure should be omitted to conform to the DRY principle, or should it be given to clarify the dependency? Or are there circumstances one solution should be preferred over the other?

推荐答案

这实际上取决于类型的用途.如果它只是为了保存实现 trait 的值,那么是的,它应该有 trait bound,例如

It really depends on what the type is for. If it is only intended to hold values which implement the trait, then yes, it should have the trait bound e.g.

trait Child {
    fn name(&self);
}

struct School<T: Child> {
    pupil: T,
}

impl<T: Child> School<T> {
    fn role_call(&self) -> bool {
        // check everyone is here
    }
}

在此示例中,学校只允许儿童进入,因此我们对结构进行了绑定.

In this example, only children are allowed in the school so we have the bound on the struct.

如果结构体打算保存任何值,但你想在实现特征时提供额外的行为,那么不,边界不应该在结构体上,例如

If the struct is intended to hold any value but you want to offer extra behaviour when the trait is implemented, then no, the bound shouldn't be on the struct e.g.

trait GoldCustomer {
    fn get_store_points(&self) -> i32;
}

struct Store<T> {
    customer: T,
}

impl<T: GoldCustomer> Store {
    fn choose_reward(customer: T) {
        // Do something with the store points
    }
}

在此示例中,并非所有客户都是金牌客户,因此在结构上设置绑定是没有意义的.

In this example, not all customers are gold customers and it doesn't make sense to have the bound on the struct.

这篇关于应该在 struct 和 impl 中复制特征边界吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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