Structs as mapping keys

Para utilizar estructuras como mapping keys, puede utilizar #[derive(Hash)] en la definición de la estructura. Esto generará automáticamente una función hash para la estructura que se puede utilizar para representar la estructura como una key en un LegacyMap.

Consider the following example in which we would like to use an object of type Pet as a key in a LegacyMap. The Pet struct has three fields: name, age and owner. We consider that the combination of these three fields uniquely identifies a pet.

#[derive(Copy, Drop, Serde, Hash)]
struct Pet {
    name: felt252,
    age: u8,
    owner: felt252,
}

#[starknet::interface]
trait IPetRegistry<TContractState> {
    fn register_pet(ref self: TContractState, key: Pet, timestamp: u64);
    fn get_registration_date(self: @TContractState, key: Pet) -> u64;
}

#[starknet::contract]
mod PetRegistry {
    use hash::{HashStateTrait, Hash};
    use super::Pet;

    #[storage]
    struct Storage {
        registration_time: LegacyMap::<Pet, u64>,
    }

    #[abi(embed_v0)]
    impl PetRegistry of super::IPetRegistry<ContractState> {
        fn register_pet(ref self: ContractState, key: Pet, timestamp: u64) {
            self.registration_time.write(key, timestamp);
        }

        fn get_registration_date(self: @ContractState, key: Pet) -> u64 {
            self.registration_time.read(key)
        }
    }
}

Juega con este contrato en Remix.

Last change: 2023-10-12, commit: 90aa7c0