gpt4 book ai didi

rust - repr(transparent) 不允许将包含数组的结构视为数组

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

我需要一个结构被视为 16 个无符号整数的数组,并且传递 CreditCard 类型将是透明的,因为我将传递一个 16 个无符号整数的数组。

如何使这段代码按照设计的方式工作?

use std::fmt;
/// Credit Card type
#[repr(transparent)]
pub struct CreditCard([u8; 16]);

impl fmt::Display for CreditCard {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}{}{}{}-{}{}{}{}-{}{}{}{}-{}{}{}{}",
self[0],
self[1],
self[2],
self[3],
self[4],
self[5],
self[6],
self[7],
self[8],
self[9],
self[10],
self[11],
self[12],
self[13],
self[14],
self[15]
)
}
}
fn process_cc(card: CreditCard) {
// do whatever
println!("processed CC {}", card);
}
fn main() {
let cc: CreditCard = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
println!("cc = {}", cc);
let card_data: [u8; 16] = [1, 2, 3, 4, 2, 2, 2, 2, 9, 8, 7, 6, 5, 5, 5, 5];
process_cc(card_data);
}

Playground

error[E0608]: cannot index into a value of type `&CreditCard`
--> src/main.rs:11:13
|
11 | self[0],
| ^^^^^^^

...

error[E0308]: mismatched types
--> src/main.rs:38:16
|
38 | process_cc(card_data);
| ^^^^^^^^^ expected struct `CreditCard`, found array of 16 elements
|
= note: expected type `CreditCard`
found type `[u8; 16]`

最佳答案

根本不是 repr(transparent) 的目的。坦率地说,我很困惑你发现了这样一个小众功能却没有阅读 the documentation for it :

Structs with this representation have the same layout and ABI as the single non-zero sized field.

这与类型在类型系统中的行为方式无关,仅与类型值的内存结构方式有关。

你想做的事情甚至不属于强类型语言。您不能只是将数组分配给另一种类型,因为它是另一种类型。使用 repr(transparent),将位从一个位转换为另一个位是有效的,但这永远不会自动发生。

更好的选择是为你的类型实现DerefFrom:

use std::ops::Deref;

impl Deref for CreditCard {
type Target = [u8; 16];

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl From<[u8; 16]> for CreditCard {
fn from(other: [u8; 16]) -> Self {
CreditCard(other)
}
}

然后取任何可以变成CreditCard的类型:

fn process_cc(card: impl Into<CreditCard>) {
// do whatever
println!("processed CC {}", card.into());
}

另见:


如果您执意要使用 repr(transparent),则需要执行以下操作:

fn process_cc(card: [u8; 16]) {
use std::mem;
let card: CreditCard = unsafe { mem::transmute(card) };
// do whatever
println!("processed CC {}", card);
}

这通常是一个非常糟糕的主意,您很可能不应该这样做。

关于rust - repr(transparent) 不允许将包含数组的结构视为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56590513/

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