1

I'm new to solidity and just have a quick question regarding structs:

struct structName {
    uint256 structNumber;
    string structString;
}

Firstly, I've seen structNumber and StructName be called "members", am I wrong to be calling them variables?

Secondly, if they are indeed variables, are they local or state variables?

Thanks in advance.

2 Answers 2

0

structs enable you to create data types with multiple properties. structs basically are a collection of variables, which can be of different data types. In this sense, you can imagine a struct as a grouping of similar variables in a custom data type defined by you, the developer.

The variables defined in a struct are also called members of the respective struct.

If you define your struct in your contract, it is treated as state variable, but you can also declare it outside of you contract and import it in another contract (See also example here). You can also use your struct in a function, with the storage keyword you access the state directly, while the memory keyword will copy it in memory.

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

contract StructExample {

    // state
    struct Person {
        uint256 age;
        string name;
    }

    // accesses state variable directly
    function storageDemo() public {
        Person storage person;
        // your code here
    }

    // copies state variable to memory
    function memoryDemo() public {
        Person memory person;
        // your code here
    }
}
2
  • Thank you so much, this is incredibly helpful! Commented Nov 3, 2022 at 19:27
  • What happens, when I don’t provide any keyword?
    – tjwelde
    Commented Jan 20 at 11:06
1

StructName is called a variable and structNumber is also called a variable. Structs are custom-defined data types that can group multiple variables in a single struct variable to form a new type. They are state variables if defined outside a function but inside a contract, and they are local variables if defined inside a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.