我有一个自定义类型:
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];
那么我为什么会得到编译错误?
repr(transparent)
就是我需要的。 - Nulikrepr(transparrent)
不起作用了,我得到了这个错误:期望32个元素的数组,但发现了结构体Address
。 - Nulik#[repr(transparent)]
,但这是一个不好的建议。除非进行像mem::transmute
这样的操作,否则几乎没有人会想使用布局表示。关于此建议的后果,请参见 repr(transparent) does not allow a struct containing an array to be treated like an array。 - Shepmastertypedef
。我建议添加一个#[repr(transparent)]
,因为在编写时似乎有可能存在填充项,所以我打算通过它来节省一些空间,但我想编译器通常知道得更好。 - Optimistic Peach