Hey @Darius311,
Breaking it down and thinking about like this should help …
-
When we define a struct, we are creating our own customised data structure. It’s customised because the developer decides which properties the data structure contains, and in what order. The struct itself is like a template, and the smart contract can create struct instances based on this template.
-
When we define a variable in Solidity we always have to state two things:
(i) the data type it will hold (uint
, int
, string
, bool
etc.) comes first
(ii) its name comes last
Other keywords can also be included to define data location (e.g. memory
), visibility (e.g. public
) or to define a payable
address. These will be included between the data type and the name of the variable.
-
When we define a variable that will hold a struct instance, this also has to be given a name and a data type. A struct instance’s data type is the name of the struct used to create it (the template upon which it has been based).
struct Product {
uint id;
uint price;
}
function createProduct(uint _id, uint _price) public {
Product memory product = Product(_id, _price);
// etc.
}
-
In the above example, the name of the local variable happens to be the same as the name of the struct. However, they only look the same to us. When the code is compiled and executed, the fact that the name of the struct (Product
) starts with a capital letter, whereas the name of the local variable (product
) starts with a lower-case letter, is enough for the computer to treat them as separate identifiers.
The convention is in fact to start struct names with a capital letter and variable names with a lower case letter.
-
In the above example, Product
is …
(i) the name of the struct,
(ii) the data type of the local variable product
(which means this variable can only hold data structures based on the template defined in the Product
struct), and
(iii) the data type of the struct instance created and assigned to the local variable product
: Product(_id, _price)
(if it didn’t have data type Product
, it couldn’t be assigned to a variable defined with data type Product
)
-
However, we could also use a completely different name for either the struct (and therefore our customised data type) or the local variable e.g.
struct Item {
uint id;
uint price;
}
function createProduct(uint _id, uint _price) public {
Item memory product = Item(_id, _price);
// etc.
}
Let us know if it still doesn’t make sense