Reputation: 3713
I need to store a mapping between a string to items which are 128 bytes long in a solidity
contract. The problem is that the longest bytes data type is bytes32
, which is not long enough, and if I try to store my strings in a string array
I get the following error:
This type is only supported in the experimental ABI encoder. Use "pragma experimental abiencoderv2;" to enable this feature
So I cannot use bytes32
because it's not big enough. I cannot use bytes
because it's not supported. And I cannot use string[]
because it's experimental and not recommended in production.
Any solution?
This is the contract I'm using:
pragma solidity ^0.4.24;
contract SomeData {
struct Data {
string id;
string[3] items;
}
mapping (string => Data) dataItems;
function addData(string id, string[3] items) public {
Data memory data = Data(id, items);
data.id = id;
data.items = items;
dataItems[id] = data;
}
function getDataItems(string id) public view returns (string[3]){
return dataItems[id].items;
}
}
Upvotes: 1
Views: 4409
Reputation: 10991
Since you know the maximum length of each individual string
, you can use a static 2 dimensional array:
contract SomeData {
struct Data {
string id;
byte[128][100] items;
}
mapping (string => Data) dataItems;
function addData(string id, byte[128][100] items) public {
Data memory data = Data(id, items);
data.id = id;
data.items = items;
dataItems[id] = data;
}
function getDataItems(string id) public view returns (byte[128][100]){
return (dataItems[id].items);
}
}
Note, only 2-dimensional dynamic arrays are not allowed. You could even use byte[128][]
if you wanted to.
Upvotes: 1