W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
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ù)組和結構等非值類型,包括bytes
and 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; } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: