1

Given this contract

contract C {
    struct Product { uint price }
    Product[] storage products;

    function doSomething() {
        products.push(Product({price: 100}));
        products.push(Product({price: 200}));
        products[0] = products[1];
        products[1].price = 300;
    }
}

Is the final price of products[0] 200 or 300?

(As a followup n00b question, how can I run a single function like this in Solidity so that I can see what the result is, without launching the contract on the blockchain?)

2

Is the final price of products[0] 200 or 300?

It is 200 because assignment from storage to storage always creates a copy as you can see here.

"All other assignments to storage always copy. Examples for this case are assignments to state variables or to members of local variables of storage struct type, even if the local variable itself is just a reference."

As the other answer pointed out, the easiest way to test code is probably Remix.

1
1

You can use Ethereum Remix to test your contract without deploying it: https://remix.ethereum.org

Testing it on Remix it seems the values of arrays are not referencing:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract C {
    // correct syntax
    struct Product { 
        uint price;
    }
    // 'products' is declared as contract property,
    // thus it's already a state variable
    // no need to make it 'storage'
    Product[] products;

    function doSomething() public {
        products.push(Product({price: 100}));
        products.push(Product({price: 200}));
        products[0] = products[1];
        products[1].price = 300;
    }

    // for _index = 0 it will return price 200
    // for _index = 1 it will return price 300
    function getProductAtIndex(uint _index) public view returns(Product memory) {
        return products[_index];
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.