Cyfrin Updraft.

帖子

分享您的知识。

Cyfrin Moderator Pst.
Mar 29, 2024
专家问答

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
分享
评论
.

答案

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
官方答案
评论
.

你知道答案吗?

请登录并分享。

Cyfrin Updraft is an education platform specializing on teaching the next generation of smart contract developers

200帖子201答案
Sui.X.Peera.

赚取你的 1000 Sui 份额

获取声誉积分,并因帮助 Sui 社区成长而获得奖励。