What's the appropriate way to update a struct via a function only if the parameters exist? For example

struct MyStruct {
  bytes32 someThing
  bytes32 someOtherThing

function updateStruct(bytes32 someThing, bytes32 someOtherThing) public {
  // get struct
  if (someThing) {
    struct.someThing = someThing;
  if(someOtherThing) {

I only want to update the fields of the struct if the argument is passed into the function. If it's null or undefined I don't want to update the struct with that value.

  • You can use somethig.length>0 for your if condition. Feb 4, 2018 at 19:55
  • But what if its not bytes32 ? @PrashantPrabhakarSingh
    – pizzarob
    Feb 4, 2018 at 19:55
  • I guess I will post a solution as comment will be too long. :) Feb 4, 2018 at 19:58
  • I am going to create separate functions for updating each different value
    – pizzarob
    Feb 4, 2018 at 21:58
  • If it's null or undefined - this is not Javascript. Jun 25, 2018 at 4:06

1 Answer 1


So since your function has 2 parameters, you always have to pass 2 arguments. Now it depends on the type of function argument.

bytes32, you can use:

if(something.length != "")

If you have string, you can convert it to bytes32,

bytes memory testSomething= bytes(something);
if(testSomething.lenght > O)

If you have uint,

if(something > 0) 

In case of address:

if(something != 0x)
  • For bytes32 the length is always 32, so you cannot use length to check for null with bytes32. But you can compare to zero if (something != 0) { } (the same trick applies with the address type). Also you cannot cast from bytes32 to bytes, if something is bytes32 then bytes(something) throws a compilation error.
    – Ismael
    Feb 4, 2018 at 20:39
  • 1
    @Ismael I was not asking to convert bytes32 to bytes, I was saying if you have string params you can convert it to bytes and then check for length, ref: here. I need to check for bytes32, I thought this will be same as converting string to bytes 32. Please update the answer if you have a solution to check for empty value of bytes32. Feb 5, 2018 at 4:42

Your Answer

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

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