Public State Getters
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 28 of 53.
Adding public to a state variable makes the compiler generate a getter callable from outside the contract. It does not generate a setter. Inside the contract, read the variable directly by name. Public visibility controls the interface, not whether blockchain storage is secret.
Declare this at contract scope:
uint256 public score;Use it inside the provided main function:
score = 32;
console.log(score);The declaration uint256 public score creates a getter named score for external callers. Inside main, the bare name reads the state variable. Writing it still requires contract code; public does not let callers directly assign storage.
A public state variable gets an external getter, not an automatic setter.
Challenge
EasyDeclare uint256 public total. Set total to the supplied amount inside main and print it.
The tests pass arguments to main in this order: uint256 amount. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 amount) external {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground