1

Is it possible to access struct field from Yul? Ideally it could look like this:

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

contract Sample {
    struct S {
        uint256 n;
        bytes b;
    }
    function foo(S memory s) external {
        uint256 len;
        assembly {
            len := mload(s.b);
        }
    }
}

If no, then what is the best way to access s.b fiels?

  1. Define variable in solidity: bytes memory localB = s.b;
  2. Some other way.
0

1 Answer 1

2

Yes, by using the mload opcode:

pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;

contract Sample {
    
    struct S {
        uint256 n;
        bytes b;
    }
    
    function foo(S memory s) external pure returns (uint256 _x, bytes memory _y) {
        assembly {
            _x := mload(s)
            _y := mload(add(s,0x20))
        }
    }
}

To test the function in Remix, you can use the following tuple: [1, "0xaa00ff"].

2
  • Thanks! It works although not as convenient as possible since it is hard to manually calculate offsets for the struct field when struct is more complicated. Oct 30, 2020 at 7:59
  • @VitalyDrogan Yes. In case you are interested, in the following question you can see the same method applied to a nested struct: ethereum.stackexchange.com/questions/77238/…
    – alberto
    Oct 30, 2020 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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