struct Balance{
uint totalBalance;
uint numPayment;
mapping(uint=>Payment) public payments;
}
Can I make the mapping public inside the struct??
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityHere the code,
mapping(uint=>Payment) public payments;
uint is the data type and Payment is not. Payment may be struct. the mapping works on storing one data type into another. like mapping(uint => address) or mapping(address => uint).
yes, but you need to remove public keyword, assuming Payment is a valid data type as Mazharul mentioned
although I don't follow the design, something like this doesn't throw compile errors
pragma solidity ^0.8.7;
contract test {
struct Payment{
uint amount;
uint timeStamp;
}
struct Balance{
uint totalBalance;
uint numPayment;
mapping(uint => Payment) payments;
}
}
A struct is an abstract data structure, struct member don't have any visibility.
Only variables that are defined using the struct type can have visibility modifiers.
Therefore, you should delete the public
keyword from your mapping. You would only want to specify the visibility if you were to declare a mapping of Balance
types, e.g. if you want to make it internal
:
mapping(address => Balance) internal balances;
A struct
defines a new Type consisting of members. Think "string", "bool", etc. Type is not an instance, so there's nothing to inspect.
You would have to make an instance with something like Balance public b
, and b
would be viewable via a "free" getter that is roughly:
function b() public view returns(Balance memory) {
return b;
}
But there's a problem. The "free" getter is compiler sugar and it is not smart enough to handle a nested mapping
like this:
pragma solidity 0.8.14;
contract StructMapping {
struct Foo {
mapping(uint => uint) bars;
}
mapping(address => Foo) public fooBars;
}
But you can work it out yourself. Since the mapping leads to a struct that contains a mapping there are two indexes in play (the part the compiler sugar doesn't handle). You can make a function to tell it what to do:
contract StructMapping2 {
struct Foo {
mapping(uint => uint) bars;
}
mapping(address => Foo) private fooBars;
function getFooBar(address foo, uint bar) public view returns (uint) {
return fooBars[foo].bars[bar];
}
}
Hope it helps.