0

I'm following this thread to store iterable data in a mapping by referencing a struct. (code sample here) However when trying to return information I simply get empty values (I'm sending correct data through a JS test script):

console screenshot

The retrieval function is just like this one:

function getInstructor(address _address) view public returns (uint, string memory, string memory) {
    return (instructors[_address].age, instructors[_address].fName, instructors[_address].lName);
}

Needless to say, I'm using Solidity 0.8.0.

I'd appreciate a lot your input.

1 Answer 1

0

First of all, you have many code issues that rendered you code uncompilable. Looks were using a lot of non-Solidity syntax. I had to perform the following edits to make your code compile:

pragma solidity ^0.5.0;

contract Courses {

    struct Instructor {
        uint age;
        string fName;
        string lName;
    }

    mapping (address => Instructor) instructors;
    address[] public instructorAccts;

    function setInstructor(address _address, uint _age, string memory _fName, string memory _lName) public {
        Instructor memory instructor = instructors[_address];

        instructor.age = _age;
        instructor.fName = _fName;
        instructor.lName = _lName;

        instructorAccts.push(_address) -1;
    }

    function getInstructors() view public returns (address[] memory) {
        return instructorAccts;
    }

    function getInstructor(address _address) view public returns (uint, string memory, string memory) {
        return (instructors[_address].age, instructors[_address].fName, instructors[_address].lName);
    }

    function countInstructors() view public returns (uint) {
        return instructorAccts.length;
    }

}

After making these edits, it is clear where the issue lies. Observe the following line:

Instructor memory instructor = instructors[_address];

The line defines the instructor in memory, which means any modifications to it would simply disappear after function execution is over. There is no object aliasing here. When you copy a created struct from storage to memory, any changes done to the memory struct would not reflect to storage. You need to copy the memory-based instructor into storage after being done with the modifications by placing the following line near the end of the function declaration:

instructors[_address] = instructor;
1
  • Thanks! It's functional now. And I apologize for the issues on that sample, I should have checked it out before sharing.
    – juanguren
    Commented Oct 3, 2021 at 1:04

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.