1

I have a struct defined in a library (to call it from different contracts):

library DataTypes {
    struct Test{
        uint256 a;
        uint256 b;
}

when i want to initialize it or update in my contract :

import {DataTypes} from "./libraries/DataTypes.sol";

Contract A {
   mapping(uint => DataTypes.Test) public tests;
   function init(){
       DataTypes.Test storage test = DataTypes.Test(1, 2);
   }
}

i get this error :

Type struct DataTypes.Test memory is not implicitly convertible to expected type struct DataTypes.Test storage pointer.

but when i define the struct in my Contract it works without any error .

Contract A {
   struct Test{
       uint256 a;
       uint256 b;
   }
   mapping(uint => DataTypes.Test) public tests;
   function init(){
       DataTypes.Test storage test = DataTypes.Test(1, 2);
   }
}

My question is : why am i getting this error ? and how can i solve this while keeping the struct in the library ?

anyone could help please ? PS: im using 0.8.12 compiler version .

2 Answers 2

1

I think Antionio offered a good explanation. But I wanted to write a code that implements the functionality you asked for (Initializing and updating the library DataType inside your contract)

Hope it helps; happy Christmas.

//SPDX-License-Identifier: UNLICENCED

pragma solidity 0.8.3;  

library DataTypes {
    struct Test{
        uint256 a;
        uint256 b;
    }
}

contract A {

   mapping(uint => DataTypes.Test) public tests;

   DataTypes.Test variableName;

   function init() public {
       variableName = DataTypes.Test(1, 2);
   }

    function getVariableName() public view returns(DataTypes.Test memory) {
       return variableName;
   }


}
1

A library doesn't have storage, and you cannot declare state variables. For this reason, you received the error message related to storage. Thus, to fix this error, you should change this line:

DataTypes.Test storage test = DataTypes.Test(1, 2);

To this:

DataTypes.Test memory test = DataTypes.Test(1, 2);

In your second example, since you have declared the struct body inside a contract and the latter can hold variable into storage you don't receive issue.

More information about libraries here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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