1

enter image description here

struct Balance{
      uint totalBalance;
      uint numPayment;
      mapping(uint=>Payment) public payments;
    }

Can I make the mapping public inside the struct??

4 Answers 4

0

Here 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).

2

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;
    }
}
1

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;
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.