Richard Zhang
Richard Zhang

Reputation: 111

Cannot pass in generic type to a struct initialization

I am trying to initalize a struct H256 and passing in data as the parameter. Here is the trait and struct definition:

/// An object that can be meaningfully hashed.
pub trait Hashable {
    /// Hash the object using SHA256.
    fn hash(&self) -> H256;
}

/// A SHA256 hash.
#[derive(Eq, PartialEq, Serialize, Deserialize, Clone, Hash, Default, Copy)]
pub struct H256(pub [u8; 32]); // big endian u256

impl Hashable for H256 {
    fn hash(&self) -> H256 {
        ring::digest::digest(&ring::digest::SHA256, &self.0).into()
    }
}

Here is another struct's method where I initalize the struct H256:

impl MerkleTree {
    pub fn new<T>(data: &[T]) -> Self
    where
        T: Hashable,
    {
        let a = H256(data);

    }
...
}

Here is the error :mismatched types expected array [u8; 32]found reference&[T]`

What is the problem?

Upvotes: 1

Views: 69

Answers (1)

HyunWoo Lee
HyunWoo Lee

Reputation: 125

The answer is simple. When you make the struct H256, the inner must be list of bytes with 32 element. However, when you call H256(data);, data has type &[T], and it is not the list of bytes with 32 element.

+) It seems that you want to hash the list of T, the type can be hashed. Then what you need to do is,

  1. You must indicate how to hash the object of type T.
  2. You must indicate how to hash the list of hashable type.

You achieve 1, by trait bound Hashable in function MerkleTree::new. So you need to do implement trait for &[T] when T is bounded by trait Hashable.

Upvotes: 1

Related Questions