Struct in Solidity

 struct type are use to represent a  records 

Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −

  • Title
  • Author
  • Subject
  • Book ID

Defining a Struct

To define a Struct, you must use the struct keyword. The struct keyword defines a new data type, with more than one member. The format of the struct statement is as follows −

struct Book { 
   string title;
   string author;
   uint book_id;
}

Accessing a Struct and its variable


To access any member of a structure, we use the member access operator (.).

The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the struct to define variables of structure type. The following example shows how to use a structure in a program.

pragma solidity ^0.5.0;

contract test {
   struct Book { 
      string title;
      string author;
      uint book_id;
   }
   Book book;

   function setBook() public {
      book = Book('Learn Java', 'TP', 1);
   }
   function getBookId() public view returns (uint) {
      return book.book_id;
   }
}



















































Comments

Popular posts from this blog

Git and Github

bubble short Q1

Java Program to Check Whether the String Consists of Special Characters