Solidity

Solidity Assignment

Solidity Assignment Main Tips

  • In Solidity assigning values to variables is a rather common task of a contract.
  • Assignment may be a little more complicated in the case of structs and arrays.

Solidity Assignment Destructuring And Returning Multiple Values

Internally, Solidity does allow tuple types, for example, a list of objects that are potentially of different types whose size at compile-time is a constant.

These tuples may be used for returning more than one value at a same time and assigning them to one or more variables (or LValues, generally speaking) at once:

Example

pragma solidity ^0.4.0;

contract C1 {
    uint x;
    function C1(uint y) payable {
        x = y;
    }
}

contract C2 {
    C1 d = new C1(4); // To be executed as a part of C2's constructor

    function createC1(uint arg) {
        C1 newC1 = new C1(arg);
    }

    function createAndEndowC1(uint arg, uint amount) payable {
        // Create and send the Ether
        C1 newC1 = (new C1).value(amount)(arg);
    }
}

 

Try on Remix Try live on Hosting


Solidity Assignment Arrays and Structs

The semantics regarding assignments are a little more complicated for types that are non-value, such as arrays and structs. If you assign to a state variable an independent copy will always be created. However, assigning to a variable that is local will create an independent copy, but only for elementary types, for example, static types which fit into 32 bytes.

If arrays or structs (this includes bytes and string) get assigned from a state variable to a local one, the local variable will hold a reference to the original state variable.

The second assignment to the local variable will not modify the state, only changing the reference itself. However, assigning to elements (or members) of the local variable will change the state.

Read previous post:
Solidity Contract Creation Via New

Solidity Contract Creation Via New Main Tips In Solidity you can create contracts via the keyword new. This way of creating...

Close