-1

My package has a structure like this.

src
├── block.rs
├── main.rs
└── traits
    ├── hashable.rs
    └── mod.rs

In hashable.rs,

pub trait Hashable {
    fn bytes(&self) -> Vec<u8>;

    fn hash(&self) -> Vec<u8> {
        crypto_hash::digest(crypto_hash::Algorithm::SHA256, &self.bytes());
    }
}

I tried to use mod to import Hashable trait from block.rs like this

mod traits;

type BlockHash = Vec<u8>;

pub struct Block {
    pub index: u32,
    pub timestamp: u128,
    pub payload: String,
    pub nonce: u64,
    pub hash: BlockHash,
    pub prev_hash: BlockHash,
}

impl Block {
    pub fn new(index: u32, timestamp: u128, payload: String, nonce: u64, prev_hash: BlockHash) -> Self {
        Block {
            index,
            timestamp,
            payload,
            nonce,
            hash: vec![0; 32],
            prev_hash,
        }
    }
}

but this didn't work. I just can use this from main.rs file, so how I can use Hashable trait from block.rs file.

Văn Đô
  • 1
  • 1
  • 1
    `block.rs` doesn't even use `Hashable`. How do you know that it's not working? What does "not working" even mean? What happens when you try to compile this? Please include all relevant compiler output in your question. – cdhowie Feb 14 '22 at 02:06
  • 1
    Instead of saying "This didn't work", it is often good to say what happened instead. Especially if there is some concrete error message that the compiler spit out. – Caesar Feb 14 '22 at 05:45

1 Answers1

0

When you say "This didn't work", you mean, you got an error message like?

error[E0583]: file not found for module `traits`
 --> src/block.rs:1:1
  |
1 | mod traits;
  | ^^^^^^^^^^^
  |
  = help: to create the module `traits`, create file "src/block/traits.rs" or "src/block/traits/mod.rs"

For more information about this error, try `rustc --explain E0583`.

If so, you have two options:

  • If your "traits" are actually logically a part of the "block"s, do move src/traits to a new folder src/block/traits
  • Or, more likely: Move the mod traits; declaration to src/main.rs, and add a use crate::traits; or use super::traits; to src/block.rs.
Caesar
  • 6,733
  • 4
  • 38
  • 44