问题答案 12026年5月26日 23:23
How to return mapping list in Solidity? (Ethereum contract)
In Solidity, a mapping is a very useful data structure that helps us map keys to values. However, due to security and efficiency considerations, Solidity does not allow directly returning the entire mapping from a function. The mapping itself does not store a list of all its keys internally; it can only access the corresponding values through individual keys.SolutionUse arrays to store keys and values: We can create two arrays, one for storing keys and another for storing values. Then return these two arrays from the function.Create access functions: For each specific key, we can create a function that takes a key as a parameter and returns the corresponding value.Use structs: If the relationship between keys and values is more complex, we can use structs to store each key and its corresponding value, then use an array to store these structs.Example CodeHere is an example using arrays and structs to store and return mapping data:ExplanationIn this contract, we define an struct to store keys and values.There is an array to store all objects.The function is used to add new key-value pairs to the array.The function allows us to access specific key-value pairs by index.The function returns the entire array, allowing us to access all key-value pairs.In this way, although we do not directly return a mapping, we provide a method to store and retrieve the keys and values of mapping-type data structures. This approach also facilitates handling and displaying data in the frontend or other smart contracts.