In hardhat fund-me -- why can we access a mapping or array by passing parameters to a function? #563
-
I'm curious about this. There are 2 related questions here. This is around 11:24:00 into the video while writing tests. We first define a mapping as and we treat this like an array of sorts where we can update the value like That's cool. But while testing, @PatrickAlphaC does as you can see, it is referred to by passing Now I think I recall Philip mentioning that public variables by default have getters and setters or something of that sort. Does this mean that a mapping (or even an array) has a getter as well? So if I pass the address, I get the output of the address? Or is the logic completely different lol. Another related question - just immediately after the above, the Here also 0 is passed as a parameter (rather than something like fundMe.funders [0] ), which is the index of the array to retrieve a value from. So is it that in the case of an array, passing the index returns the value at that index, while in the case of a mapping, passing an index returns the value of that index? Is this just how it works? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you have a public state variable of array type, then you can only retrieve single elements of the array via the generated getter function. This mechanism exists to avoid high gas costs when returning an entire array. You can use arguments to specify which individual element to return, for example, myArray(0). The same applies to mappings. You should read more here: https://docs.soliditylang.org/en/v0.8.13/contracts.html#getter-functions |
Beta Was this translation helpful? Give feedback.
If you have a public state variable of array type, then you can only retrieve single elements of the array via the generated getter function. This mechanism exists to avoid high gas costs when returning an entire array. You can use arguments to specify which individual element to return, for example, myArray(0).
The same applies to mappings.
You should read more here: https://docs.soliditylang.org/en/v0.8.13/contracts.html#getter-functions