1. 程式人生 > >3. Solidity智慧合約struct型別

3. Solidity智慧合約struct型別

本小節討論Solidity智慧合約的struct型別,Struct是Solidity中的自定義型別。使用Solidity的關鍵struct進行自定義。

結構體內還可以再包含字串,整型,對映,結構體等複雜型別,

先看以下例項

1. 基本的結構體

 struct Product{       

        uint productId;
        uint productValue;    

    }

2. 在Store中定義Product結構體

結構體通常需要定義在一個合約當中

contract Store{


    struct Product{
        
        uint productId;
        
        uint productValue;
    
    }
    
    

}

3. 構造結構體物件

contract Store{

    struct Product{
        
        uint productId;
        
        uint productValue;
    
    }

    function save() public {
        
        Product  memory product = Product(2,93);
   
    }
    

}

4. 結構體應用例項

4.1 將以下程式碼拷貝到http://remix.ethereum.org/中

contract Store{

    struct Product{
        
        uint productId;
        
        uint productValue;
    
    }
    
    mapping (uint=>Product) products;
    
    function save() public {
        
        Product  memory product = Product(2,93);
        
        products[120]=product;
        
    }

    function getPriceOfProductId(uint productId) public view returns (uint){
        
        return products[productId].productValue;
        
    }
 

}

4.2 編譯並執行合約

編譯並建立合約例項後,點選右下角的“save”後,在“getPriceOfProductId”右邊輸入120,再點選“getPriceOfProductId“後,右邊出現93,則說明合約呼叫成功

本節主要討論了struct型別,最後一個例項涉及到mapping等知識點,請參考作者其他文章

關注公眾號,並回復“區塊鏈技術專案開發”,下載ppt和sol檔案