I'm learning about the struct data type and I want to know if:
- it's possible to return multiple instances of a struct object at the same time.
- an instance declared locally (inside a function) can return its value.
I want to get the details of all the instances (book1, book2, and book3) returned to me at the SAME TIME. I ran the code and could only get the details for ONE INSTANCE at A GIVEN TIME. So, the two instances I declared at state-level (book1 and book2) returned values WHEN CALLED SEPARATELY. However, book3, which was declared locally, didn't return its value when called. What I got was a declaration error (DeclarationError: Undeclared Identifier).
- How do I return all the values together?
- Why is book3 not returning its value? Can't a struct have a local instance?
pragma solidity >=0.4.0 <0.9.0;
// Creating a struct contract
contract MyStruct {
// Declaring a struct
struct Book {
string name;
string writer;
uint id;
bool available;
}
// Declaring a structure object, book1 (state variable of type struct; no values)
Book book1;
// Assigning values to fields for another struct instance, book2
Book book2 = Book ("Building Ethereum DApps", "Roberto Infante", 2, false);
// Defining a function to set values for the fields for structures
function setBookDetails() public {
// Assigning values to book 1 (state struct above)
book1 = Book("Introducing Ethereum and Solidity", "Chris Dannen", 1, true);
// Defining a new book instance locally, book3 (local struct)
Book memory book3 = Book ("Solidity Programming Essentials", "Ritesh Modi", 3, true);
}
// Defining function to print book1 details
function getBookDetails() public view returns (string memory, string memory, uint, bool) {
return (book1.name, book1.writer, book1.id, book1.available);
//return (book2.name, book2.writer, book2.id, book2.available);
//return (book3.name, book3.writer, book3.id, book3.available);
}
}