I came across quite a common problem that it seems I can't solve elegantly and efficiently in solidity.
I've to pass an arbitrary long array of arbitrary long strings to a solidity contract.
In my mind it should be something like
function setStrings(string [] row)
but it seems it can't be done.
How can I solve this problem?
String arrays as parameters aren't supported yet in solidity. Show activity on this post. You can convert the array elements to a byte string and then deserialize that byte string back to the array inside the function.
Solidity provides a data type named string to declare variables of type String. It also extends support for string literals using single-quotes ' and double-quotes " . A String can also be created using the string constructor.
concat() Since it's not possible to concatenate the strings with “ + ” or “ append ” in solidity , we will use the memory bytes to concatenate the strings in method 2. A special method called bytes. concat allows us to easily concatenate the strings in solidity.
This is a limitation of Solidity, and the reason is that string
is basically an arbitrary-length byte array (i.e. byte[]
), and so string[]
is a two-dimensional byte array (i.e. byte[][]
). According to Solidity references, two-dimensional arrays as parameters are not yet supported.
Can a contract function accept a two-dimensional array?
This is not yet implemented for external calls and dynamic arrays - you can only use one level of dynamic arrays.
One way you can solve this problem is if you know in advanced the max length of all of your strings (which in most cases are possible), then you can do this:
function setStrings(byte[MAX_LENGTH][] row) {...}
As of Solidity 0.8.0, ABIEncoderV2
, which provides native support for dynamic string arrays, is used by default.
pragma solidity ^0.8.0;
contract Test {
string[] public row;
function getRow() public view returns (string[] memory) {
return row;
}
function pushToRow(string memory newValue) public {
row.push(newValue);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With