为什么新类型不使用内部类型的特征? [英] Why don't newtypes use the traits from the inner type?

查看:41
本文介绍了为什么新类型不使用内部类型的特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 rust 1.0.0-nightly 中,这段代码可以正常工作:

In rust 1.0.0-nightly, this code works fine:

fn main() {
    let x = 10f64;
    let y = 20f64;
    let z = x + y;
    println!("z = {}", z);
}

但是如果我尝试使用 newtype(根据 锈书):

But if I try to use a newtype (according to the rust book):

struct Metres(f64);

fn main() {
    let x = Metres(10f64);
    let y = Metres(20f64);
    let z = x + y;
    println!("z = {}", z);
}

我收到此编译器错误:

test.rs:6:13: 6:18 error: binary operation `+` cannot be applied to type `Metres`
test.rs:6     let z = x + y;
                      ^~~~~
error: aborting due to previous error

既然Metres基本上就是一个f64,那为什么编译器不能用同样的+操作符,创建一个新的z?

Since Metres is basically a f64, why can't the compiler use the same + operator, and create a new Metres object for z?

如果我不能做添加之类的简单事情,我该如何使用新类型?它们如何非常有用"(正如书中所说的那样)?

How can I use newtypes if I can't do simple things like adding and such? How are they "very useful" (as the book calls them)?

(有一个 关于这个的老问题,但是生锈的变化很大,因此我重新提问)

(There is an old question about this, but rust changes a lot, hence I'm reasking)

推荐答案

newtypes 以这种方式工作的原因通常是因为您希望避免在基础类型上定义的特征.例如,您可以有 MetresFeet,它们都包装 f64 但定义了 Metres英尺进行单位转换,普通的f64加法不会给你.

The reason newtypes work this way is generally because you want to avoid the traits defined on the underlying type. For example, you could have Metres and Feet which both wrap f64 but define addition of Metres and Feet to do unit conversion, which plain f64 addition doesn't give you.

当然,有时您确实需要底层 trait 实现.目前,您必须自己编写包装器实现,但有一个 RFC 可以自动生成这些实现:https://github.com/rust-lang/rfcs/issues/479

Of course, sometimes you do want the underlying trait implementation. Currently, you'd have to write a wrapper implementation yourself, but there is an RFC for the ability to generate these automatically: https://github.com/rust-lang/rfcs/issues/479

这篇关于为什么新类型不使用内部类型的特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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