1

I have the following code in solidity:

pragma solidity ^0.4.18;

contract testcontract {
    function testme () returns (string){
        string mystring = "foo2";
        return "foo";
    }
}

And I get the following TypeError:

browser/dummy2.sol:5:9: TypeError: Type literal_string "foo2" is not implicitly convertible to expected type string storage pointer.
    string mystring = "foo2";
    ^----------------------^

If I just do string mystring;, I don't get the error, and as the TypeError describes, there is an issue with the assigning of the "foo2" value to the string mystring, but I can't figure out why this is happening. Does this mean that variables can't be declared and initiated inside functions? I don't have the issue when it's outside of the function and within the contract.

6

To fix, you need to set mystring in memory since storage is the default.

pragma solidity ^0.4.18;

contract testcontract {
    function testme () returns (string){
        string memory mystring = "foo2";
        return "foo";
    }
}

If you set a string within a function, since the default is storage, it will look for you to set that memory string as the pointer of the storage string...and not a string literal.

Example:

contract testcontract {
    string mystringStorage = "Blah";

    function testme () returns (string){
        // String Literal Set In Memory
        string memory mystring = "foo2";

        // String Set From a Pointer
        string mystringMemory = mystringStorage;

        return "foo";
    }
}

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.