如何在自定义类型上实现 fmt::Display?

Nul*_*lik 3 rust

我有这个自定义类型:

pub type Address = [u8; 32];
Run Code Online (Sandbox Code Playgroud)

我尝试fmt::Display为这种类型实现:

impl fmt::Display for Address {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let public_key = sr25519::Public::from_raw(self);
        let address = public_key.to_ss58check();
        write!(f,"{}",address)
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个编译错误:

pub type Address = [u8; 32];
Run Code Online (Sandbox Code Playgroud)

我知道要实现一个特征,我需要有两个之一:type本地的定义或本地的定义trait

好吧,我已经在本地定义了类型:

pub type Address = [u8; 32];
Run Code Online (Sandbox Code Playgroud)

那么为什么我会收到编译错误呢?

Opt*_*ach 5

这里的问题是以下没有声明新类型:

pub type Address = [u8; 32];
Run Code Online (Sandbox Code Playgroud)

但取而代之的是一个类型别名,它更接近于 c 风格的 typedef。这意味着您的代码将变成以下内容:

impl fmt::Display for [u8; 32] {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let public_key = sr25519::Public::from_raw(self);
        let address = public_key.to_ss58check();
        write!(f,"{}",address)
    }
}
Run Code Online (Sandbox Code Playgroud)

而这里,[u8; 32]不是本地类型。您可能想要做的是使用所谓的newtype模式。#[repr]如果您的类型可能有一些填充,您可能希望为其添加一个属性。