0

I have a contract and need to check, if the String-Array inside a Struct is of a mapping is set. I found this answer: What is the zero value for a string? I convert my String to Bytes and check if it's unequal 0.

I tried the same. Here is my code.

contract MyContract{

struct artist { string name; string[] songNames; }

mapping(address => artist) artists;

function checkDefaultValue() public view returns (uint256) { return bytes(artists[msg.sender].name).length; }

}

I compiled and migrated it with truffle and got the following:

BN {
  negative: 0,
  words: [
    25535600,       45482263,
    41138111,       21965320,
    15007926,       53592304,
    65526573,       9237065,
    33654519,       3241105,
    <1 empty item>
  ],
  length: 10,
  red: null
}

The problem is, the length is 10. Then I set the string with the following function:

   function Upload(string memory _songName) public {
      artists[msg.sender].songNames.push(_songName);
   }

But only the words changed, after I run the function: checkDefaultValue(). The length is still 10.

What am I doing wrong or how to I check, if the String is set from a specific address? And I want to do it with required. Not an if.

Luca F
  • 3
  • 1

2 Answers2

1

how about a different approach to the test, and what's returned, which might be easier.

check for length and return true/false

here I'm just passing in a string or "" as a logic tester

function isDefault(string memory _str) public pure returns (bool) {
    if(bytes(_str).length == 0) return true;
    return false;
}
sola24
  • 1,238
  • 3
  • 20
0

The contract, as written, is returning zero (try it in Remix), so the focus should be on the testing methodology. Consider passing the BN to .toString() to see a lossless representation of the decimal value.

You can make a nice little pure function for this concern:

function isNull(string memory val) internal pure returns (bool) {
  return bytes(val).length == 0;
}

and then use it to validate input:

require(!isNull(inputStr), "input cannot be empty");

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145