2

I have question about creating Struct where size of array passed to that struct could have different lengths. As in code below I could pass to this Recipe 2 ingredients, 3 ingredients or whatever amount if ingredients I would like with corresponding array of amounts.

Unfortunately I'm getting error:

TypeError: Invalid type for argument in function call. Invalid implicit conversion from uint8[2] memory to uint256[] memory requested.

I know that this comes from that I am passing fixed array size to dynamic array pole in Struct, what could be solution for that, if I want to be able to pass different sizes of arrays?

pragma solidity ^0.4.2;

contract Game {
    address public owner;

    // RECIPES
    mapping(uint256 => Recipe) private recipeInfo;

    struct Recipe {
        uint256 recipeId;
        uint256[] ingredientId;
        uint256[] ingredientAmount;
        uint256 ethCost;
    }

    // constructor of game;
    function Game() public {
        owner = msg.sender;
        recipeInfo[1] = Recipe(1, [1, 5], [100, 100], 50000000);
        recipeInfo[2] = Recipe(2, [2, 3, 4], [100, 200, 300], 100000000);
    }
}
  • have tried the explicit conversion ? uint256[]([1,5]) – Kaki Master Of Time Apr 2 '18 at 9:44
  • Yes I have tried: but Explicit type conversion not allowed from "uint256[2] memory" to "uint256[] memory" – Pacxiu Apr 2 '18 at 11:46
3

From https://solidity.readthedocs.io/en/v0.4.21/types.html#array-literals-inline-arrays:

Note that currently, fixed size memory arrays cannot be assigned to dynamically-sized memory arrays, i.e. the following is not possible:

// This will not compile.

pragma solidity ^0.4.0;

contract C {
    function f() public {
        // The next line creates a type error because uint[3] memory
        // cannot be converted to uint[] memory.
        uint[] x = [uint(1), 3, 4];
    }
}

It is planned to remove this restriction in the future but currently creates some complications because of how arrays are passed in the ABI.

For now, I suppose you'd have to do something like this:

uint256[] memory foo = new uint256[](2);
foo[0] = 1;
foo[1] = 5;
recipeInfo[1] = Recipe(1, foo, ...);
| improve this answer | |
  • Hey, thanks. It worked. I was aware of that, fom solidity and couldn't get around it. Is this approach efficient in terms of gas cost? – Pacxiu Apr 2 '18 at 11:34
  • I don't know, sorry. – user19510 Apr 2 '18 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.