You check that a value is defined in the mapping by checking it is not zero.

If an explicit setting of zero has meaning for your application, you need auxiliary data (or structure) to track when a value of zero has been explicitly set.

A lightweight approach would be to add a bool property to the struct (say named initialized), and to set it to true when the zero is explicitly set. As all bools are false (0) by default, you can check against the value true.

Alternatively, check that each member of the struct is zero. If a member is a string, cast it to bytes and then check its length is zero.

For an example see How to test if a struct state variable is set

Another data structure or mapping may be needed depending on the application.


Here is a related example on using a pair to check the meaning of zero:

contract C {
    uint[] counters;
    function getCounter(uint index)
        returns (uint counter, bool error) {
            if (index >= counters.length) return (0, true);
            else return (counters[index], false);
        }
    function checkCounter(uint index) {
        var (counter, error) = getCounter(index);
        if (error) { ... }
        else { ... }
    }
}
Answer from eth on Stack Exchange
🌐
Medium
hamilton-cyber.medium.com › empty-of-struct-string-array-or-mapping-in-solidity-43f09a4d5fb
Empty of Struct, String, Array or Mapping in Solidity | by Hamilton Cyber | Medium
October 20, 2022 - Two following ways can be used ... to be new’ed for its members to be accessible, where all the members are empty with their members having zero-value of each type....
Discussions

blockchain - how to initialize Empty array in stuct [Solidity] - Stack Overflow
I want to initialize the comments(struct member) with Empty Array(Type: Comment). Which code should I use for The Problem Point?? ... Honestly, I don't know how solve this problem. I changed store a little bit, now it works, maybe it will be helpful for you · P.s in 0.4.25 version you can return all post comments, but in 0.5.1 I assume that its not support as default yet · pragma solidity ... More on stackoverflow.com
🌐 stackoverflow.com
solidity - Check if a struct is empty - Ethereum Stack Exchange
I have a function where I pass a id. With that id the contract find in a mapping a struct. My idea is to check if exists that struct with the given id with a if clause. I try with 0, null, "". I... More on ethereum.stackexchange.com
🌐 ethereum.stackexchange.com
Creating an empty array to intitialise new struct

How about:

Cart storage c = carts[msg.sender];
c.total = 0;
//whatever else you need to store in the newly created cart;

In solidity, all values in a mapping are virtually initialized, so you can straight access them and their members.

More on reddit.com
🌐 r/ethdev
5
1
June 10, 2022
if statement - How to test for an empty structure being returned via a Solidity function()? - Stack Overflow
Here is a sample Solidity contract where I have a function which returns an empty struct. I want to test from a function inside the contract for the empty struct, but I am having trouble figuring o... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2022
🌐
Solidity by Example
solidity-by-example.org › structs
Structs | Solidity by Example | 0.8.26
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; contract Todos { struct Todo { string text; bool completed; } // An array of 'Todo' structs Todo[] public todos; function create(string calldata _text) public { // 3 ways to initialize a struct // - calling it like a function todos.push(Todo(_text, false)); // key value mapping todos.push(Todo({text: _text, completed: false})); // initialize an empty struct and then update it Todo memory todo; todo.text = _text; // todo.completed initialized to false todos.push(todo); } // Solidity automatically creates a getter for 'todos' so // you don't actually need this function.
🌐
Stack Exchange
ethereum.stackexchange.com › questions › 65708 › check-if-a-struct-is-empty
solidity - Check if a struct is empty - Ethereum Stack Exchange
Add a bool valid field to your struct, set it to true whenever you add a struct to the mapping, and use it in order to check whether or not the struct is valid (i.e., whether or not it "exists").
🌐
Morioh
morioh.com › p › e6c9f9e40ce7
how to initialize Empty array in stuct [Solidity] - Morioh
I am suffering to initialize an empty array for struct when a struct is made.
🌐
Reddit
reddit.com › r/ethdev › creating an empty array to intitialise new struct
r/ethdev on Reddit: Creating an empty array to intitialise new struct
June 10, 2022 -

I've been sorting out a relatively complex smart contract and running across an odd problem that I don't know how to deal with. The core concept is demonstrated by this vastly simplified example.

pragma solidity ^0.4.14;

contract ShoppingCart {
   
    mapping(address => Cart) carts;

    struct Cart {
        uint total;
        uint dateBought;
        Purchase[] purchases;
    }

    struct Purchase {
        uint productCode;
        uint price;
    }

    function createCart() {
        carts[msg.sender] = Cart('Target', 0, now, Purchase[]);
    }

    function addProductToCart(uint productCode, uint price){
        carts[msg.sender].purchases.push(Purchase(productCode, price));
        carts[msg.sender].total += price;
    }
}

The issue lies in this createCart example. Creating a blank purchase array is not sufficient to satisfy the function required in the struct, you get the following compiler error.

Invalid type for argument in function call. Invalid implicit conversion from type(struct ShoppingCart.Purchase memory[] memory) to struct ShoppingCart.Purchase memory[] memory requested.

For a start this compiler error is utterly useless. It's literally saying I can't convert from one type to an identical type. I've heard of similar issues coming up when importing, but this doesn't seem related.

I've seen a few theoretical solutions, but they were frankly awful, and there has to be a nice solution. How do you initialise a struct that contains an array? Please don't link me to the docs. I've read them intently and if they have a solution I don't know what i'm looking for.

Truffle v4.0.0-beta.0 (core: 4.0.0-beta.0)
Solidity v0.4.15 (solc-js)
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72369941 › how-to-test-for-an-empty-structure-being-returned-via-a-solidity-function
if statement - How to test for an empty structure being returned via a Solidity function()? - Stack Overflow
May 24, 2022 - contract MyNFTShop is ERC721 { struct NFTCardAttributes { uint256 cardIndex; string name; string imageURI; } NFTCardAttributes[] defaultCards; constructor( string[] memory cardNames, string[] memory cardImageURIs, ) ERC721("NFT", "NFTC") { for (uint256 i = 0; i < cardNames.length; i += 1) { defaultCards.push( NFTCardAttributes({ cardIndex: i, name: cardNames[i], imageURI: cardImageURIs[i], }) ); NFTCardAttributes memory c = defaultCards[i]; } } function checkIfUserHasNFTCard() public view returns (NFTCardAttributes memory) { uint256 userNFTCardNftTokenId = nftCardHolders[msg.sender]; if(userNF
🌐
Stack Exchange
ethereum.stackexchange.com › questions › 110890 › mapping-of-a-struct-returns-empty-fields
solidity - Mapping of a struct returns empty fields - Ethereum Stack Exchange
October 2, 2021 - The line defines the instructor in memory, which means any modifications to it would simply disappear after function execution is over. There is no object aliasing here. When you copy a created struct from storage to memory, any changes done ...
🌐
Stack Overflow
stackoverflow.com › questions › 72075908 › unable-to-initialize-empty-mapping-using-solidity-solana
struct - Unable to initialize empty mapping using solidity solana - Stack Overflow
May 1, 2022 - https://ethereum.stackexchange.com/questions/62784/how-to-initialize-a-new-struct-with-an-empty-mapping ... Save this answer. ... Show activity on this post. You can try to initialize your campaigns mapping in this way: // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract CrowdFunding { // Defines a new type with two fields.
Top answer
1 of 3
24

There is no need to initialize storage arrays in Solidity. Only memory arrays has to be initialized before usage.

So in your case, no need to initialize x inside Bar as long as you are not assigning a value to one of the x indexes inside your foobar. Actually, making initialization in your code will consume gas for no reason.

The following code works well for your case:

function foobar(address a) public {
    Bar memory b;
    b.owner = a;
    //When 'b' is pushed to 'bars' array:
    // (1) 'b' will be converted from memory to storage.
    // (2) And 'x' inside it will be initialized automatically.
    bars.push(b); 
}

However, if you need to access x and push some value you can use push:

function foobar2(address a, uint x0) public {
    Bar memory b;
    b.owner = a;
    bars.push(b);
    //Trying: b.x[0] = x0; will generate error. Since, b.x is a memory array that is not initialized!
    bars[bars.length - 1].x.push(x0); //This will work fine!
}

Actually, you can still initialize your memory array, as an empty one, as follow:

function foobar3(address a) public {
    Bar memory b = Bar(a, new uint); //Thanks to "James Duffy" for his answer.
    bars.push(b);
}

Last thing to mention is that: If you have multi values, that you need to insert to your x array, then you can do this as follow:

function foobar4(address a, uint[] _x) public {
    Bar memory b = Bar(a, _x);
    bars.push(b);
}

Or as follow. But, this will consume more gas:

function foobar5(address a, uint[] _x) public {
    Bar memory b;
    b.owner = a;
    bars.push(b);

    Bar storage c = bars[bars.length - 1]; // Get the newly added instance of the storage struct
    for (uint i = 0; i < _x.length; i++) {
        c.x.push(_x[i]);
  }

Check full code at the nice EthFiddler: https://ethfiddle.com/fQI6Khgz3E

2 of 3
3

Working fiddle:

https://ethfiddle.com/Yn6fLiAjto

One way to make this work is to create your temporary Bar in memory before pushing it to bars (Bar memory b instead of Bar storage b). Solidity will then automatically copy the struct data from memory to storage. See: https://ethereum.stackexchange.com/a/4476/22415 for more details.

Also new uint[] is a function which requires a size argument, e.g. new uint.

So in full, that line should read Bar memory b = Bar(a, new uint);

🌐
Medium
medium.com › coinmonks › structs-in-solidity-924e1f2e38cc
Structs in Solidity. 100 days of solidity (Day 13–17) | by Favorite_blockchain_lady | Coinmonks | Medium
August 10, 2023 - Here, we first declare an empty person3 struct and then assign values to its fields individually. This method gives you flexibility in assigning values separately. By deploying and interacting with this contract, you can see how each method ...
🌐
Stack Overflow
stackoverflow.com › questions › 72750723 › how-a-struct-is-taking-an-empty-array-and-later-how-an-address-is-going-to-be-pu
blockchain - How a struct is taking an empty array and later how an address is going to be put there? - Stack Overflow
June 25, 2022 - But how in this line Room memory room = Room(new address[](0), 0, 0); Room struct is taking an empty array and later how an address is going to be put there? pragma solidity ^0.4.18; contract StructArrayInit { event OnCreateRoom(address indexed _from, uint256 _value); struct Room { address[] players; uint256 whosTurnId; uint256 roomState; } Room[] public rooms; function createRoom() public { Room memory room = Room(new address[](0), 0, 0); rooms.push(room); rooms[rooms.length-1].players.push(msg.sender); OnCreateRoom(msg.sender, 0); } function getRoomPlayers(uint i) public view returns (address[]){ return rooms[i].players; } } blockchain ·
🌐
GitHub
github.com › ethereum › solidity › issues › 12385
Compiler refuses to generate a getter if omitting struct fields would leave a nested struct empty · Issue #12385 · argotorg/solidity
December 8, 2021 - Description The compiler refuses to generate a getter for a struct if omitting all dynamic array and/or mapping fields would leave it empty. There's however a case where this happens even if the outer struct would not actually be empty. ...
Author   argotorg
🌐
Stack Exchange
ethereum.stackexchange.com › questions › 72888 › initialising-empty-arrays-structs-in-struct-based-storage-graph-structures
solidity - Initialising Empty Arrays & Structs In Struct-based Storage Graph Structures? - Ethereum Stack Exchange
The concept of “undefined” or “null” values does not exist in Solidity, but newly declared variables always have a default value dependent on its type. To handle any unexpected values, you should use the revert function to revert the whole transaction, or return a tuple with a second bool value denoting success. In your example - instead of creating the new struct in memory and then using push to append it to the storage array, you can increase the length of books[_bookID].chapters which will initialize a new, empty ChapterData struct.
🌐
GitHub
github.com › hyperledger-solang › solang › issues › 785
Unable to initialize empty mapping as described in solidity documentation · Issue #785 · hyperledger-solang/solang
May 1, 2022 - // ========== ERROR BELOW =========== // campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); campaigns[campaignID] = Campaign({ beneficiary: beneficiary, fundingGoal: goal, numFunders: 0, amount: 0 }); } function contribute(uint campaignID) public payable { Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage.
Author   hyperledger-solang