多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 赋值(Assignment) ## 解构赋值和返回多个结果(Destructing Assignments and Returning Multip Values) Solidity内置支持`元组(tuple)`,也就是说支持一个可能的完全不同类型组成的一个列表,数量上是固定的(Tuple一般指两个,还有个Triple一般指三个)。 这种内置结构可以同时返回多个结果,也可用于同时赋值给多个变量。 ``` pragma solidity ^0.4.0; contract C { uint[] data; function f() returns (uint, bool, uint) { return (7, true, 2); } function g() { // Declares and assigns the variables. Specifying the type explicitly is not possible. var (x, b, y) = f(); // Assigns to a pre-existing variable. (x, y) = (2, 7); // 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). // If the tuple ends in an empty component, // the rest of the values are discarded. (data.length,) = f(); // Sets the length to 7 // The same can be done on the left side. (,data[3]) = f(); // Sets data[3] to 2 // Components can only be left out at the left-hand-side of assignments, with // one exception: (x,) = (1,); // (1,) is the only way to specify a 1-component tuple, because (1) is // equivalent to 1. } } ``` ## 数组和自定义结构体的复杂性(Complication for Arrays and Struts) 对于非值类型,比如数组和数组,赋值的语法有一些复杂。 - 赋值给一个状态变量总是创建一个完全无关的拷贝。 - 赋值给一个局部变量,仅对基本类型,如那些32字节以内的`静态类型(static types)`,创建一份完全无关拷贝。 - 如果是数据结构或者数组(包括`bytes`和`string`)类型,由状态变量赋值为一个局部变量,局部变量只是持有原始状态变量的一个引用。对这个局部变量再次赋值,并不会修改这个状态变量,只是修改了引用。但修改这个本地引用变量的成员值,会改变状态变量的值。