dkx22
dkx22

Reputation: 1133

Solidity storage struct not compiling

I'm new to solidity and I'm just experiencing with some simple code. Basically I just want to create a struct that will store data permenantly inside a contract. According to the doc I need storage for that. But the following code is not compiling except if I use memory instead. Why?

pragma solidity ^0.4.11;
contract test {

struct Selling {
    address addr;
    string name;
    uint price;
}

mapping(string => Selling) selling;

function sellName() constant returns (bool ok)
{
    address a = 0x4c3032756d5884D4cAeb2F1eba52cDb79235C2CA;
    Selling storage myStruct = Selling(a,"hey",12);
}
}

The error I get is this:

ERROR:
browser/test.sol:16:9: TypeError: Type struct test.Selling memory is not implicitly convertible to expected type struct test.Selling storage pointer.
        Selling storage myStruct = Selling(a,"hey",12);
        ^--------------------------------------------^

Upvotes: 2

Views: 4790

Answers (2)

Adam Kipnis
Adam Kipnis

Reputation: 10971

When you first create the myStruct instance, it will be created in memory and then written out to storage (assuming you put the object into your selling map and don't declare your method constant) when the function returns. If you were to retrieve the item from your map in another function, then you would declare it as a storage variable.

See this explanation on Ethereum StackExchange for more details. The Solidity documentation also has a very good explanation of how variables are stored and when to use memory vs storage.

Upvotes: 4

Adrian Ciura
Adrian Ciura

Reputation: 1112

I had similiar situation, the fix for this was:

function sellName() constant returns (bool ok)
{
    address a = 0x4c3032756d5884D4cAeb2F1eba52cDb79235C2CA;
    Selling memory myStruct = Selling(a,"hey",12);
    // insert 'myStruct' to the mapping:
    selling[a] = myStruct;
}

Upvotes: 2

Related Questions