2

I'm going through the Ethereum Pet Shop Truffle tutorial and found this in the test section:

address adopter = adoption.adopters(8);

A previous section had used adopters[petId] = msg.sender;

Why does one use [] and the other ()?

1
  • It's a Solidity language feature - it generates getters for public storage variables, including arrays and mappings Nov 14, 2017 at 23:39

3 Answers 3

2

The tutorial says that,

address[16] public adopters; is a public state variable. Therefore, according to the Solidity docs,

The compiler automatically creates getter functions for all public state variables.

What you are seeing here: address adopter = adoption.adopters(8); is the tutorial accessing the automatically generated getter for the public adopters state variable.

Here is a simple example I created, to explain this for you:

enter image description here

Put this in the Solidity online compiler to see the outputs are as expected.

3

Where you see the square brackets, an array element is being accessed from within the same contract. This is a direct read or write to the array.

Where you see the curved brackets, it's usually a function call, most commonly made from outside the contract.

If an array is marked public, the compiler automatically creates an accessor function that takes the index you're calling as a parameter. This is what's happening with adoption.adopters(8); The adoption contract has a function called adopters, which is the equivalent of:

function adopters(uint idx) public constant {
    return adopters[idx];
}

You also occasionally see curved brackets with an array in a different context, where it is being used to initialize an in-memory array of a particular length. The following will create an in-memory array of 8 addresses:

address[] memory adopters = new address[](8);
2

The () is a function call.

In the tutorial, you'll see that the adopters array is public:

address[16] public adopters;

In Solidity, all public attributes of a contract automatically result in a getter with the same name being created; that is what you are seeing being called.

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.