Search code examples
ethereumsolidity

Invalid implicit conversion from literal_string to string storage pointer requested


I am trying to add a candidate thorough a construct.

contract Election{
    struct Candidate {
        uint id;
        string name;
        uint voteCount;
    }

    mapping(uint => Candidate) public candidates;

    uint public candidatesCount;

    constructor () public {
        addCandidate('Candidate 1');
        addCandidate('Candidate 2');
    }

    function addCandidate(string storage _name) private {

        candidatesCount ++;
        candidates[candidatesCount] = Candidate(candidatesCount,_name,0);
    }


}

Expected to add Candidate 1 and 2. but facing this error: Invalid implicit conversion from literal_string "Candidate 1" to string storage pointer requested. addCandidate('Candidate 1'); ^-----------^


Solution

  • You are using storage in your addCandidate function header, whereas these are memory variable. Do change to memory and you will good to go.

    function addCandidate(string memory _name) private
    

    For more insights about storage and memory keywords, have a look here. Hope it will save your problem.