0

Trying to understand memory in blockchain for sharing reference of array as common storage for multiple mappings.

Let's say there is a need for following relationships. So there will be products keep created and added into the products array. I would like to create mapping of the product with some key in uint256 and also mapping for the customer to products relationship, shown below.

Product[] Products;
mapping(uint256 => Product) ProductsMap;
mapping(address => mapping(uint256 => Product) CustomerProductsMap;

So let's say there was new product created with unique id in uint256,

uint256 Id = 1;
Product memory newProduct =  Product({
   id: Id,
   name: "toy",
   price: 100000
});

And we add this to array, for quick GET external function.

Products.push(newProduct);

And we add key-val pair for quick look up, such that:

ProductsMap[Id] = newProduct; 

And now, I would like to create customer - product relationship using the same instance.

CustomerProductsMap[customerAddress][Id] = newProduct;

So here is the question, When the value of newProduct updated such that:

ProductsMap[1].price = 200000

Can I assume that this product's price now changed regardless of which map / array I use to look up? I hope they all referencing to same memory.

1 Answer 1

0

No, you have created three copies of the same data.

Can't recommend something for this case but usually having a mapping from ID to Product and storing ID instead of Product.

1
  • yeah I figured out.. oh well seems mappings can't pass references.
    – swcraft
    Sep 16, 2021 at 22:37

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.