Solidity Keywords

更新时间:
复制 MD 格式

Ant Blockchain supports Solidity syntax that is largely consistent with the official Solidity documentation. For details, see Solidity documentation.

Function syntax

A Solidity function declaration has the following structure:

function (<parameter types>) {public | private | internal | external} [modifier] [pure|constant|view|payable] [returns (<return types>)]

A function declaration consists of:

  • Parameter types and return types

  • A visibility keyword (public, private, internal, or external)

  • One or more optional modifier keywords (pure, constant, view, payable, or a custom modifier)

Visibility keywords

Visibility keywords control which code can call a function or access a state variable.

KeywordBehavior
publicAccessible from outside and inside the contract. A public state variable automatically generates a getter function. Functions default to public when no visibility is specified.
privateAccessible only within the contract where it is defined. Derived contracts cannot inherit, call, or access private members.
internalAccessible within the contract and its derived contracts. When used with the using for keyword, the contract can also access internal functions of the referenced contract. State variables default to internal when no visibility is specified.
externalCallable only from outside the contract.

Modifier keywords

modifier

The modifier keyword defines a custom execution condition for a function. A function with a modifier runs only when the modifier's requirements are satisfied.

Use _; inside the modifier body to mark where the function body executes.

modifier onlyAdmin() {
    require(msg.sender == admin, "Permission denied");
    _;
}

function set(uint a) public onlyAdmin returns(uint) {
    .....
}

In this example, set can only be called by the admin address. The _; statement marks where the function body runs after the modifier check passes.

constant

State variables declared as constant must be assigned a fixed value at the time of declaration. The value must be determinable during the compilation process.

The following assignment sources are not allowed for constant variables:

  • Memory references

  • Blockchain data, such as now, this.balance, or block.number

  • Execution data, such as msg.gas

  • Calls to external contracts

Only value types and strings can be declared as constant.

pure

A function or state variable declared as pure can only be read and cannot be modified.

view

A function or state variable declared as view cannot be read or modified.

Data locations

Solidity variables are stored in one of two locations, which determines their lifecycle.

LocationKeywordBehavior
Persistent storagestorageVariables are permanently stored on the blockchain.
Temporary memorymemoryVariables exist only during the execution of an external function call. They are discarded when the call completes.