任務

2022-05-12 17:34 更新

解構賦值并返回多個值

Solidity 內部允許元組類型,即可能不同類型的對象列表,其編號在編譯時是一個常數(shù)。這些元組可用于同時返回多個值。然后可以將它們分配給新聲明的變量或預先存在的變量(或一般的 LValues)。

元組在 Solidity 中不是正確的類型,它們只能用于形成表達式的句法分組。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;

contract C {
    uint index;

    function f() public pure returns (uint, bool, uint) {
        return (7, true, 2);
    }

    function g() public {
        // Variables declared with type and assigned from the returned tuple,
        // not all elements have to be specified (but the number must match).
        (uint x, , uint y) = f();
        // Common trick to swap values -- does not work for non-value storage types.
        (x, y) = (y, x);
        // Components can be left out (also for variable declarations).
        (index, , ) = f(); // Sets the index to 7
    }
}

不能混合變量聲明和非聲明賦值,即以下內容無效:(x, uint y) = (1, 2);

筆記

在 0.5.0 版本之前,可以分配給較小尺寸的元組,或者填充在左側或右側(曾經(jīng)是空的)?,F(xiàn)在不允許這樣做,因此雙方必須具有相同數(shù)量的組件。

警告

在涉及引用類型時同時分配多個變量時要小心,因為它可能導致意外的復制行為。

數(shù)組和結構的復雜性

對于數(shù)組和結構等非值類型,包括bytesand string,賦值的語義更為復雜,有關詳細信息,請參閱數(shù)據(jù)位置和賦值行為。

在下面的示例中,調用對g(x)on 沒有影響,x因為它在內存中創(chuàng)建了存儲值的獨立副本。但是,h(x)成功修改,x 因為只傳遞了一個引用而不是一個副本。

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.22 <0.9.0;

contract C {
    uint[20] x;

    function f() public {
        g(x);
        h(x);
    }

    function g(uint[20] memory y) internal pure {
        y[2] = 3;
    }

    function h(uint[20] storage y) internal {
        y[3] = 4;
    }
}
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號