3

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) {
    struct.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.

pizzarob
  • 435
  • 1
  • 5
  • 15

1 Answers1

0

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)
Prashant Prabhakar Singh
  • 8,026
  • 5
  • 40
  • 79
  • 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 04 '18 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. – Prashant Prabhakar Singh Feb 05 '18 at 04:42