Solidity – How to Get the Default Value of String in Solidity Using Truffle

soliditytruffle

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.

Best Answer

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;
}
Related Topic