- Mastering Ethereum
- Merunas Grincalaitis
- 220字
- 2021-06-24 15:01:04
Visibility of variables
Every variable and function in Solidity has a specific visibility. The visibility is a keyword you use after the variable type to define who should have access to it:
- Public: This means that the variable can be read or written by any contract, including external ones, as long as there's a function to update them.
- Private: Private variables can't be accessed by a derived smart contract, those that implement your contract with the is keyword; for example, contract Example is Another {}, where Another is a smart contract with private variables that can't be accessed by Example.
- External: These variables and functions are not accessible by the contract containing them. Only external contracts and users can use them.
- Internal: These are variables and functions that can't be read or written by external entities, only by the contract itself or by inherited contracts, as you saw in the example for the private variable.
To keep things simple, I recommend you to always write public for your variables unless it's a special variable, which doesn't happen that often. If you don't define any visibility, the variable will be public by default, although it's better to just write the public keyword in every variable to make sure that you understand the visibility of the variable and it's not a mistake.