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

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

我是 Solidity 的新手,我一直在尝试创建和获取 STRUCT 而不将其添加到数组中。我总是看到 Structs with arrays 和 .push 方法,我想在没有它的情况下尝试一下。

我已经创建了一个合约,其中包含一个结构和一个用于创建和获取它的函数。

如果我创建一个 public 函数来创建,而不是 return,该结构不会给我任何错误...如下所示:

    struct Todo {
    string name;
    uint age;
}

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

}

对于上面的代码,我还想知道为什么它不允许我将指针“Todo”设置为如下存储:Todo storage myTodo = Todo(_name, _age); 它给出类型错误:Todo 内存不可隐式转换为期望类型结构存储指针。

接下来,我尝试修改函数以创建和 RETURN 但是当我开始收到 ParseError 时。

代码如下:

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

}

我还在“returns(struct), returns(struct memory)”中尝试了 aobve 代码......

非常感谢任何类型的帮助。

非常感谢

您收到此错误是因为您错误地在 getTodo() 函数上设置了 returns 关键字。在您的情况下,您必须以这种方式更改您的功能:

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

如果你想处理存储结构,请看这个智能合约代码:

// 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];
    }
}