Solidity - 基本語法



一個 Solidity 原始檔可以包含任意數量的合約定義、匯入指令和pragma指令。

讓我們從一個簡單的 Solidity 原始檔開始。以下是一個 Solidity 檔案的示例:

pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {
   uint storedData;
   function set(uint x) public {
      storedData = x;
   }
   function get() public view returns (uint) {
      return storedData;
   }
}

Pragma

第一行是一個 pragma 指令,它說明原始碼是為 Solidity 0.4.0 或更高版本編寫的,這些版本不會破壞直到(但不包括)0.6.0 版本的功能。

pragma 指令始終是區域性於一個原始檔的,如果您匯入另一個檔案,則該檔案中的 pragma 不會自動應用於匯入檔案。

因此,一個 pragma 指令,它要求編譯器版本不早於 0.4.0,也不晚於 0.5.0,可以這樣寫:

pragma solidity ^0.4.0;

這裡第二個條件是透過使用 ^ 新增的。

合約

Solidity 合約是程式碼(其函式)和資料(其狀態)的集合,它駐留在以太坊區塊鏈上的特定地址。

uint storedData 行聲明瞭一個名為 storedData 的狀態變數,其型別為 uint,set 和 get 函式可以用來修改或檢索變數的值。

匯入檔案

雖然上面的例子沒有匯入語句,但 Solidity 支援與 JavaScript 中非常相似的匯入語句。

以下語句從 "filename" 匯入所有全域性符號。

import "filename";

以下示例建立一個新的全域性符號 symbolName,其成員是 "filename" 中的所有全域性符號。

import * as symbolName from "filename";

要從與當前檔案相同的目錄匯入檔案 x,請使用 import "./x" as x;。如果您改為使用 import "x" as x;,則可能引用全域性“包含目錄”中的不同檔案。

保留關鍵字

以下是 Solidity 中的保留關鍵字:

abstract after alias apply
auto case catch copyof
default define final immutable
implements in inline let
macro match mutable null
of override partial promise
reference relocatable sealed sizeof
static supports switch try
typedef typeof unchecked
廣告
© . All rights reserved.