0

I want a function that creates document in my contract. I removed anything unnecessary. Goes like this:

contract MyContract{
  mapping (uint => document) documents;

  struct document{
      address author;
      bytes32 hashedContent;
  }

  function addDocument(bytes32 docHash) public{
      document newDoc = document (msg.sender,docHash); //*
      [...]
  }
}

Documents are structs, and I want to create them from a function and then permanently add the to a mapping. I have an error at the //* line saying:

MyContract.document memory is not implicitly convertible to expected type struct MyContract.document storage pointer. document newDoc = document (docHash,msg.sender); ^---------------------------------------------^

(from Remix) The left part is storage but I think the left part is memory.

Is it possible to do what I'm trying to do?

  • If so, what did I do wrong?
  • If not, do you know a workaround? (Someone suggested that I do a separate contract for every document but it would complicate everything A LOT considering the rest of my contract and preferably I'm looking for a solution in a single contract.
2

You can just do this:

documents[whateverInt] = document(msg.sender,docHash);

If you absolutely need to declare the document before setting it, you need to do this:

document memory newDoc = document(msg.sender,docHash);
documents[whateverInt] = (doc);

Otherwise newDoc will default to being a storage pointer, but the document(msg.sender,docHash) will be a value and not a pointer.

  • Pushing a memory structs in a storage mapping converts it to storage? – Teleporting Goat Feb 28 '18 at 16:41
  • In a way. More accurately, document(msg.sender, docHash) isn't treated as a memory pointer or a storage pointer, it's a value. If you assign the value to a memory pointer, it works correctly, but if you assign it to a storage pointer, it will overwrite something dangerously. – flygoing Feb 28 '18 at 16:44
  • It gives me the following error: TypeError: Member "push" not found or not visible after argument-dependent lookup in mapping(uint256 => address) – Teleporting Goat Feb 28 '18 at 16:44
  • Oops! See my edit. I answered as if you were pushing to an array, not using a mapping. – flygoing Feb 28 '18 at 16:46

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.