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

时间:2019-06-14 02:00:20

标签: rust

我需要将一个结构像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]`

1 个答案:

答案 0 :(得分:2)

这根本不是repr(transparent)的目标。坦白说,我为您发现了这样的利基功能而感到困惑,并且没有读过the documentation for it

  

具有这种表示形式的结构的布局和ABI与单个非零大小的字段相同。

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

您想要做的甚至都不真正属于强类型语言。您不能仅将数组分配给其他类型,因为它是另一种类型。使用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);
}

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