type error from bytes32 to uint256 but I properly declared it. In solidity

Viewed 50
//SPDX-License-Identifier:GPX-3.0
pragma solidity >=0.7.0 <0.9.0;

contract sol {
    struct student {
        string name;
        uint256 ID;
        string grade;
    }
    bytes32[] private student_Address;
    mapping(bytes32=>student) private studentMap;

    uint256 private index = 0;
    function createNewStudent(string memory _name, uint256 _id, string memory _grade) public {
        student_Address.push(keccak256(abi.encodePacked(index)));
        studentMap[student_Address[index]] = student(_name, _id, _grade);
        index++;
    }

    function getStudentInfo(uint256 num) public view returns (bytes32, student memory) {
        return (student_Address[num], studentMap[num]); // line 21
    }
}

where I have a problem is line 21 :return (student_Address[num], studentMap[num]);

The error message is: TypeError: Type uint256 is not implicitly convertible to expected type bytes32

but I don't understand why there's type error.

Because return type of student_Address[num] is bytes32, and I properly declared it. And uint256 num is just a index.

2 Answers

you can convert num type from uint256 to bytes32

return (student_Address[bytes32(num)], studentMap[bytes32(num)]); 

hope it work for you

The issue is not with student_Address[num], but with studentMap[num].

studentMap is a mapping where the key of type bytes32. However num is of type uint256, so you're trying to access the mapping value with an incorrect key type.

Based on how you store the data in createNewStudent(), you need to retrieve it using student_Address[num] as the key of the studentMap mapping.

function getStudentInfo(uint256 num) public view returns (bytes32, student memory) {
    bytes32 key = student_Address[num];
    return (
        key,
        studentMap[key]
    );
}
Related