Solidity – How to Return a String with Function in Solidity 0.5.1 Without Errors

solidity

Pretty new to solidity and I was watching some tutorial on web. and my function is giving an error while trying to return a string from a function.

Below is my simple contract:

pragma solidity ^0.5.1;

contract and {

    string d = "Hello";

    function getValueOfabc() public view returns(string) {
        return d;
    }
}

And function getValueOfabc() public view returns(string) { is giving me below error:

browser/mulreturn.sol:7:50: TypeError: Data location must be "memory" for return parameter in function, but none was given.
    function getValueOfabc() public view returns(string) {
                                                 ^----^ 

The above code is working fine with version 0.4.25

Best Answer

In v 0.5, explicit data location for all variables of struct, array or mapping type is now mandatory. Please note that strings and bytes also belong to the array implementation.

Hence your code must be modified as shown below to work with v0.5:

pragma solidity ^0.5.1;

contract and {

    string d = "Hello";

    function getValueOfabc() public view returns(string memory) {
        return  d;
    }
}
Related Topic