Function Definition and Access Control
Learning Objectives
Master Solidity function definition, visibility modifiers, transaction properties, modifiers, and constructors.
Function Definition
General Form
function fname([参数]) [可见性][交易属性][modifier...] returns(返回值) { ... }
- Function Signature:
fname([参数])—— uniquely identifies a function - Return Value:
returns(返回值)—— declares the function's return type
Function Visibility
Solidity provides four visibility modifiers, controlling the function's call scope:
| Modifier | Description |
|---|---|
| public | Fully visible, callable internally and externally |
| private | Visible only within this contract, not accessible by child contracts |
| internal | Visible within this contract and by child contracts (similar to Java's protected) |
| external | Callable only externally (calling internally via this generates a new message) |
Note: Variables default to
internal, and functions default topublic. This is different from other programming languages!
Visibility Diagram
A Contract├── private pri() → only within A├── internal inter() → within A + child contract B├── public pub() → fully visible ←── C contract can call└── external ext() → only externally ←── C contract can callB is A (inherits A)├── inter() accessible└── pub() accessible
Transaction Properties
Transaction properties determine whether a function modifies the on-chain state, directly affecting gas consumption:
| Property | Description |
|---|---|
| Default (no modifier) | Write operation, broadcast across the network, consensus confirmation, consumes gas |
| view | Read-only operation, reads contract state, does not consume gas (when called externally) |
| pure | Pure function, independent of contract state, only depends on input parameters |
Complete Example
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.2 <0.9.0;
contract NumberStorage {
uint public x;
// Write operation (default): modifies state, consumes gas
function setX(uint px) public {
x = px;
}
// view: read-only state
function getX() public view returns(uint) {
return x;
}
// pure: pure calculation independent of state
function add(uint a, uint b) private pure returns(uint) {
return a + b;
}
}
Function Modifier (Modifier)
Modifier is similar to AOP (Aspect-Oriented Programming), often used for access control and precondition checks.
require/revertfor conditional checks, rolling back the transaction if not met_;indicates the execution of the modified function body
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract NumberModifier {
uint private number;
modifier nonZero() {
require(number != 0, "Number is zero and cannot be processed.");
_;
}
function doubleNumber() public nonZero {
number *= 2;
}
function resetNumber() public {
number = 0;
}
}
Constructor (Constructor)
The constructor is called once when the contract is deployed, often used to initialize state variables. msg.sender is the address of the contract deployer.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Constructor {
address public owner;
uint public x;
constructor(uint _x) {
owner = msg.sender;
x = _x;
}
}
Comprehensive Example: Ownable Contract
Combining constructors, modifiers, and visibility control, we implement a permission management contract where "only the owner can operate":
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Ownable {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function setOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "invalid address");
owner = _newOwner;
}
}
Counter Contract Example
A simple counter contract, demonstrating the use of external visibility:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract Counter {
uint public count;
function inc() external {
count += 1;
}
function dec() external {
count -= 1;
}
}
主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/7491