|
| 1 | +//! This example demonstrates the `all_derives` attribute in the `sol!` macro. |
| 2 | +//! |
| 3 | +//! The `all_derives` attribute enables the derivation of standard Rust traits. |
| 4 | +use alloy::{ |
| 5 | + primitives::{Address, U256}, |
| 6 | + sol, |
| 7 | +}; |
| 8 | +use std::hash::{DefaultHasher, Hash, Hasher}; |
| 9 | + |
| 10 | +sol! ( |
| 11 | + #![sol(all_derives)] |
| 12 | + // The `all_derives` attribute enables derivation of std rust traits such as |
| 13 | + // `Default`, `Debug`, `PartialEq`, `Eq`, and `Hash`. |
| 14 | + struct Foo { |
| 15 | + uint256 a; |
| 16 | + uint64 b; |
| 17 | + address c; |
| 18 | + } |
| 19 | +); |
| 20 | + |
| 21 | +fn main() { |
| 22 | + // `Default` is derived. |
| 23 | + let foo = Foo::default(); |
| 24 | + let foo_bar = Foo { a: U256::from(1), b: 2, c: Address::with_last_byte(1) }; |
| 25 | + |
| 26 | + let mut foo_list = vec![foo.clone(), foo, foo_bar]; |
| 27 | + |
| 28 | + // `Debug` derived as well. |
| 29 | + println!("Initial foo_list: {:?}", foo_list); |
| 30 | + |
| 31 | + // `PartialEq` is derived, enabling us to apply `.dedup()`. |
| 32 | + foo_list.dedup(); |
| 33 | + assert_eq!(foo_list.len(), 2); |
| 34 | + |
| 35 | + // `Hash` is derived, enabling us to apply `.hash()`. |
| 36 | + let baz = Foo { a: U256::from(1), b: 2, c: Address::with_last_byte(1) }; |
| 37 | + let mut hasher = DefaultHasher::default(); |
| 38 | + baz.hash(&mut hasher); |
| 39 | + let hash = hasher.finish(); |
| 40 | + println!("Hash of baz: {hash}"); |
| 41 | +} |
0 commit comments