'I keep on getting ParseError: Expected type name // when I want to return a struct I have just created

I am new in Solidity and I have been trying to create and get STRUCT without adding it to an Array. I alway see Structs with arrays and the method .push and I wanted to try it without it.

I have created a single Contract with one Struct and one function to create and get it.

If I create a single public function to create, but not return, the struct it doesn´t give me any error... Like the following:

    struct Todo {
    string name;
    uint age;
}

function createTodo(string memory _name, uint _age) public pure{
    Todo memory myTodo = Todo(_name, _age);

}

With the above code I would also like to know why it wouldn´t let me set the pointer "Todo" as storage like: Todo storage myTodo = Todo(_name, _age); It gives an TypeError: Todo memory is not implicity convertible to expect type struct storage pointer.

Next, I tried to modify the function to create and RETURN but then is when I start getting the ParseError.

The code is the following:

 function getTodo(string memory _name, uint _age) public returns(struct myTodo) {
    Todo memory myTodo = Todo(_name, _age);
    return myTodo;

}

With the aobve code I also tried in "returns(struct), returns(struct memory)"....

I would really appreciate any type of help here.

Thank you very much



Solution 1:[1]

You received this error because you're wrong to set a returns keyword on getTodo() function. In your case, you must change your function in this way:

function getTodo(string memory _name, uint _age) external pure returns(Todo memory) {
        Todo memory myTodo = Todo(_name, _age);
        return myTodo;
}

If you want to handle storage structs, see this smart contract code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
    
    struct Todo {
        string name;
        uint age;
    }

    // Declare state variable
    Todo[] todoArray;

    // Push into array new struct
    function createTodo(string memory _name, uint _age) public {
        todoArray.push(Todo(_name, _age));
    }

    // Retrieve ToDo struct from specific index about struct array
    function getTodo(uint _index) external view returns(Todo memory) {
        return todoArray[_index];
    }
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kerry99