1

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?

2
  • Like error says: it expects an array of u8s but you pass slice of Ts Commented Sep 25, 2022 at 20:10
  • &[T] and [u8; 32] are not the same type. For one, the former takes an arbitrary type T, whereas the latter only has concrete types. Even correcting that (that is, considering &[u8] instead), the former is a pointer to an array, not an array. Finally, even considering [u8] instead of [u8; 32], the latter exactly has 32 elements, whereas for the second one this is a runtime information. Commented Sep 25, 2022 at 20:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.