1

is there an equivalent to javascript's spread operator in solidity?

I am hoping to do something like this

 struct Book {
      string name;
      string writer;
      string genre;
      string publisher;
   }
 
   string[] memory bookInfo = ["bookName", "bookAuthor", "bookGenre", "bookPublisher"];
   Book book1 = Book(...bookInfo);

Or is there a way to pass a struct to a constructor in solidity?

1
  • There's no spread operator on solidity. You can loop over the array and copy it's values (spend more gas) or just assign an array to another. You can even create a function that returns a memory array.
    – 0xTheL
    Commented Oct 3, 2022 at 19:52

1 Answer 1

2

There is no equivalent to JavaScript's spread operator in Solidity.

But you can initialize a struct the two following ways:

// Like a function
Book book1 = Book("book1Name", "book1Author", "book1Genre", "book1Publisher");

// Via a key-value mapping
Book book2 = Book({ name: "book2Name", writer: "book2Author", genre: "book2Genre", publisher: "book2Publisher" });

It is recommended to initialize it via a key-mapping for a better code clarity.

More examples here: https://solidity-by-example.org/structs/

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.