Here’s an article about Mappings Ethereum:
Ethereum map: a simple example
When you work with Ethereum, you often meet the concept of map. A mapping is a data structure that allows you to store values associated with specific keys (also known as «keys» or «indices») in a painting or other data structure. In this article, we will explore how to create and use a simple mapping in the global scope.
What is a mapping?
In Ethereum, a mapping is essentially a way to store values paintings that are indexed by their position in the painting. The key value pairs are stored in a single field (the «key» field), followed by an index value in another field («index» field). This allows an effective search and data to be found.
Creating a simple map
Here is a simple example of creating a map with two elements:
`Solidity
MymApping contract {
uint8 [2] public mymap;
}
`
In this example, we define a contract calledMymapping which has a series of 2 elements (uint8
) called MyMap
.
Mapa popularity
To populate data map, you can use functions that take the key and value as arguments. Let’s create two functions:
`Solidity
MymApping contract {
set of functions (UINT8 index, UNT8 value) Public {
mymap [index] = value;
}
GET FUNCT (UINT8 INDEX) Public View Return (UINT8) {
return mymap [index];
}
}
`
In the "set" function, we store the value provided at the specified index. In theGetfunction, we simply return the value associated with the given index.
using mapping
Now that we have created and populated our map, to use it to store some data:
Solidity
MymApping contract {
Mymapping MyMap;
Builder () public {
MyMap.Set (0, 1); // set the first item to index 0
MyMap.Set (1, 2); // set the second item to index 1
}
GETMYITEM function (UNT8 index) Public View Return (UNT8) {
return mymap.get (index);
}
}
`
In this example, we create a "mymapping contract and set two mapping elements using the» set «function. Then we use the Get
function to take over a mapping element.
Example of use
To test our map, let’s call the function Getmyitem
:
`Solidity
Pragma solidity ^0.8.0;
Mycontract contract {
Mymapping MyMap;
Builder () public {
MyMap.Set (1, 5); // set item to index 1 to 5
}
GETMYITEM function (UINT8 index) public returns (UINT8) {
return mymap.get (index);
}
}
`
In this example, we call the functiongetmyitem in our own contract. Because there is no article at index 0 in our mapping, the function simply returns 0.
Conclusion
Ethereum maps provide a strong way to store and take the data effectively. In this article, we explored how to create a simple mapping in the global scope using solidity. I then populated the mapping with data and used it to store and take articles. This example demonstrates the versatility of the Ethereum mapping and their potential applications in the development of smart contracts.
I hope this will help you understand the maps better! Announce -if you still have additional questions or need additional examples.
Deja una respuesta