0

If we have the following code:

pragma solidity >= 0.5;
contract stringsContract {
    function takesTwo(string memory str, uint idx) public pure returns (bytes memory) {
        bytes memory bytesStr = bytes(str);
        return bytesStr[idx];
    }
}

Why do we get TypeError return argument bytes1 is not explicitly convertible to expected type (type of first return variable bytes memory).

The fix was to change bytes memory to bytes:

contract stringsContract {
        function takesTwo(string memory str, uint idx) public pure returns (byte) {
            bytes memory bytesStr = bytes(str);
            return bytesStr[idx];
        }
    }

Nevertheless, I'm still curious about the reason of the compilation error. Any thoughts?

0

This is not returning a bytes memory, so remove [idx].

return bytesStr[idx];

Compiles:

pragma solidity 0.5.16;

contract stringsContract {

    function takesTwo(string memory str, uint idx) public pure returns (bytes memory) {
        bytes memory bytesStr = bytes(str);
        return bytesStr;
    }
}

That doesn't use idx at all. If your goal is to return one of the bytes, then the function would promise a byte.

pragma solidity 0.5.16;

contract stringsContract {

    function takesTwo(string memory str, uint idx) public pure returns (byte) {
        bytes memory bytesStr = bytes(str);
        return bytesStr[idx];
    }
}

Hope it helps;

| improve this answer | |
  • 1
    This certainly helped me reason through the error, thank you. I had a typo in the second part of my question and left the extra s in bytes; should've been byte like you mentioned. It compiled successfully. – adriaanbd Jan 3 at 6:27

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.