Cyfrin Updraft.

Post

Share your knowledge.

Cyfrin Moderator Pst.
Mar 29, 2024
Expert Q&A

Confusion About Struct Elements in Solidity: Parentheses

I'm trying to access a struct element within a contract instance. In DeployFundMe.s.sol we have

address ethUsdPriceFeed = helperConfig.activeNetworkConfig(); However, in HelperConfig.s.sol we have

contract HelperConfig is Script { NetworkConfig public activeNetworkConfig; struct NetworkConfig { address priceFeed; } ...... }

Despite understanding that helperConfig.activeNetworkConfig is a variable of type NetworkConfig, I'm confused about why I need parentheses at the end of helperConfig.activeNetworkConfig(). I've tried alternative syntaxes without success, encountering errors like 'Member 'priceFeed' not found or not visible after argument-dependent lookup in function () view external returns (address).solidity(9582).' Can someone clarify why the correct syntax requires parentheses and provide guidance on correctly accessing struct elements in Solidity?

  • Solidity
  • Smart Contract
0
1
Share
Comments
.

Answers

1
Cyfrin Moderator Ans.
Mar 29 2024, 12:18

Solidity automatically generates getter functions for the variables you store, allowing external access to them. When trying to access a specific part of a struct variable like priceFeed from a NetworkConfig type variable, the getter function returns the entire struct, not allowing selective access.

To enable selective access, you can modify the HelperConfig.sol file by adding additional elements to the struct, such as:

  struct NetworkConfig {
      address priceFeed; // ETHUSD price feed
      uint chainId; // chain ID
  }
  ```

When retrieving the struct using `helperConfig.activeNetworkConfig()`, you will receive the entire struct. Subsequently, you can choose which elements to utilize, for example:
 
```solidity
  NetworkConfig memory anvilConfig = NetworkConfig(address(mockPriceFeed), block.chainid);
  return anvilConfig;
  (address ethUsdPriceFeed, uint chainId) = helperConfig.activeNetworkConfig();
  ```

If you only need to store `chainId`, you can discard the `address` part and retain the comma, like so:

 ```solidity
  (, uint chainId) = helperConfig.activeNetworkConfig();
  ```

However, when accessing the struct from within the originating contract, you can directly access its elements without issues:

  ```solidity
  activeNetworkConfig.priceFeed
  activeNetworkConfig.chainId
  ```
This direct access is possible because within the contract, you are interacting with the actual struct, not just a reference to it.
0
Official Answer
Comments
.

Do you know the answer?

Please log in and share it.

We use cookies to ensure you get the best experience on our website.
More info