1

I want to be able to trigger runTest() and return false. I'd need to clone the struct at some point but I'm not sure how to do it in solidity. I thought passing it to another function as memory would be a clone but the original gets modified.

pragma solidity ^0.4.19;
pragma experimental ABIEncoderV2;
contract Tester {

    struct Foo {
        bool stayFalse;
    }

    function Tester() public {
    }

    function runTest() public constant returns (bool) {
        Foo memory foo;
        return one(foo);
    }

    function one(Foo memory foo) public constant returns (bool){
        Foo memory foobar;
        foobar = two(foo);
        return foo.stayFalse;
    }

    function two(Foo memory bar) public constant returns(Foo) {
        bar.stayFalse = true;
        return bar;
    }

}
1

I do not think it means what you think it means.

The problem is that you're creating a new Foo in run test, then passing it into one(), then passing it into two(), then changing it in two() returning it to one(), where you assign it into foobar, then proceed to return not even foobar's, but the original foo's stayFalse (not that it would have helped any).

Really the issue is that you've only got one Foo the whole way through, so whatever you do, you'll be changing it. You need to create a whole new copy instead.

In order to clone a struct you need to create a new one with the fields copied from the old one.

Example:

The following example contains a clone() function that creates a new Foo with the parameters from the source Foo incorporated into it.

pragma solidity ^0.4.19;
pragma experimental ABIEncoderV2;
contract Tester {
    struct Foo {
        bool stayFalse;
    }

    function Tester() public {
    }

    function runTest() public pure returns (bool, bool) {
        Foo memory foo;
        return one(foo);
    }

    function one(Foo memory foo) public pure returns (bool, bool){
        Foo memory foobar = two(clone(foo));
        return (foo.stayFalse, foobar.stayFalse);
    }

    function two(Foo memory bar) public pure returns (Foo) {
        bar.stayFalse = true;
        return bar;
    }

    function clone(Foo memory from) internal pure returns (Foo memory) {
        return Foo(from.stayFalse);
    }
}

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.