Search code examples
ethereumsolidity

How to create a function that returns me my selection between more structs in Solidity?


I am trying to create a function that would return me the struct I select from multiple structs. Here is my code:

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

contract Structing {

    struct DataOne {
        uint indexOne;
        address toOne;
        }
    struct DataTwo {
        uint indexTwo;
        address toTwo;
        }

    function selectingStruct(string name_struct) public view returns(struct) {
        return _name_struct public final_selection;
        }
}

This is the error I get:

Parser error, expecting type name.

How to create a function that returns me my selection between more structs in Solidity?


Solution

  • Your snippet only contains struct definitions, but not storage properties storing any data.

    You'll need to define the exact datatype that you want to return. There's no magic typing that would allow returning a "1 of N" type in Solidity.

    pragma solidity ^0.8;
    
    contract Structing {
        // type definition
        struct DataOne {
            uint indexOne;
            address toOne;
        }
    
        // type definition
        struct DataTwo {
            uint indexTwo;
            address toTwo;
        }
    
        // typed properties
        DataOne dataOne;
        DataTwo dataTwo;
    
        // TODO implement setters of `dataOne` and `dataTwo` properties
    
        function getDataOne() public view returns (DataOne memory) { // returns type
            return dataOne; // property name
        }
    
        function getDataTwo() public view returns (DataTwo memory) { // returns type
            return dataTwo; // property name
        }
    }