本文介绍了当 trait 和 type 都不在这个 crate 中时提供一个实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为原始类型 u8 提供一个 trait ToHex(不是我定义的,来自 serialize)的实现:

I want to provide an implementation of a trait ToHex (not defined by me, from serialize) for a primitive type u8:

impl ToHex for u8 {
    fn to_hex(&self) -> String {
        self.to_str_radix(16)
    }
}

问题是我收到这个编译器错误:

The problem is I get this compiler error:

error: cannot provide an extension implementation where both trait and type are not defined in this crate

我理解这个错误的原因及其逻辑,这是因为特征和原始类型都是我的代码的外部.但是我该如何处理这种情况并为 u8 提供一个 ToHex 实现?更一般地说,你是如何处理这种问题的,在我看来,这个问题一定很普遍,应该可以并且很容易地扩展这样的类型?

I understand the reason of this error and its logic, this is because both the trait and the primitive type are external to my code. But how can I handle this situation and provide an ToHex implementation for u8? And more generally how do you handle this kind of issue, it seems to me that this problem must be common and it should be possible and easy to extend types like this?

推荐答案

你应该使用 newtype struct 来做到这一点:

You should use a newtype struct to do this:

pub struct U8(pub u8)

impl ToHex for U8 {
    fn to_hex(&self) -> String {
        let U8(x) = *self;
        x.to_str_radix(16)
    }
}

然而,这确实意味着您应该将 u8 包装到需要执行此转换的 U8 中:

This does mean, however, that you should wrap u8 into U8 where you need to perform this conversion:

let x: u8 = 127u8

// println!("{}", x.to_hex());   // does not compile
println!("{}", U8(x).to_hex());

就性能而言,这是完全免费的.

This is absolutely free in terms of performance.

这篇关于当 trait 和 type 都不在这个 crate 中时提供一个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:59