5

Is it possible to encode a struct in Solidity without serializing each variable separately?

Something like:

struct MyStruct {
   uint x;
   uint y;
}

MyStruct storage myStruct = MyStruct({
   x: 11,
   y: 12
});

bytes memory data = abi.encode(myStruct, (MyStruct));

Or in assembly?

1
  • 1
    What do you want to do with the encoded data?
    – Kof
    Commented May 12, 2022 at 16:34

2 Answers 2

2

If you just want to store this on your contract, solidity structs are already stored encoded in storage.

Just define a data member as struct and assign values, it will be properly encoded.

In case you want to send this as a function parameter, you can just pass the struct (if that's the input type) and it will also be encoded properly.

2

The correct way to encode a struct is to spread it out while encoding.

I.e.:

abi.encode(MyStruct.x, MyStruct.y);

Make sure to pass the parameters in the right order so that you get the right values when you're retrieving the data off-chain and decoding it.

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.