Loading...
As we know that many time we want to save the details of the user or any other product or things on the fixed position we also want to fetch the user or other details of the particular things from that position when we want.For that in the solidity we mainly have different datatypes or the storages to work on such type of the condition. In this we will discuss the struct how it's decleard or save the value in it or fetch the data from it.
.....So let's get started,
First of all we will start from the How to decleard the struct.For that we used the struct product.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract product
{
struct prod
{
uint256 proId;
string Proname;
uint256 stock;
}
}
So like this way we mainly define the struct and in it we define the different datatype that for define or recoganize the particular product. In the above struct we assign the three properties of the particular product such as a proId,product name, stock of the product.After this we want to put some value in that struct for that
//assigning the array
prod[] pro;
function addproduct(uint256 proId , string memory Proname ,uint256 stock) public
{
prod memory P = prod( proId,Proname,stock);
pro.push(P);
}
we created one array as we see above who is of the prod type that is our struct and who's name is the pro then after that we create one function to add the product detail's in which we want the input from the user and that input is stored in the prod type struct into P and the pushed into the array called as the pro.
After this we want to fetch the particular product and for that we mainly assign the id to the product through which we can easily fetch the product which we want. so how can we do that i will show you.
function fetchprod(uint256 proId) public view returns(string memory proname,uint256 stock)
{
uint256 i;
for(i=0;i<pro.length;i++)
{
prod memory P =pro[i];
if(P.proId == proId)
{
return(P.proname,P.stock);
}
}
}
First we are decleard one for loop for the reading all the values on the particular position within the array. Then we get all the value on the particular position in the p and compare it with the id value provided by the user and at last it return by the function.