gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:04:42 25 4
gpt4 key购买 nike

我有这个自定义类型:

pub type Address = [u8; 32];

我尝试为这种类型实现 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)
}
}

但是我得到这个编译错误:

error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> core/linix-primitives/src/lib.rs:122:1
|
122 | impl fmt::Display for Address {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl doesn't use types inside crate

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

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

pub type Address = [u8; 32];

那么为什么会出现编译错误?

最佳答案

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

pub type Address = [u8; 32];

而是一个类型别名,它更接近于 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)
}
}

在这里,[u8; 32] 不是本地类型。您可能想要做的是使用所谓的 newtype图案。如果您的类型可能有一些填充,您可能需要向其添加一个 #[repr] 属性。

关于rust - 如何在自定义类型上实现 fmt::Display?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com