Skip to content

Instantly share code, notes, and snippets.

@TehilaFavourite
Created July 12, 2023 01:10
Show Gist options
  • Save TehilaFavourite/70e9d82091d8a98bd9dcaa6eb95a5efc to your computer and use it in GitHub Desktop.
Save TehilaFavourite/70e9d82091d8a98bd9dcaa6eb95a5efc to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract StructArrayExample {
struct Person {
string name;
uint age;
}
Person[] public people;
// Pushing a struct into the array
function addPerson(string memory _name, uint _age) public {
Person memory newPerson = Person(_name, _age);
people.push(newPerson);
}
// Creating a struct and pushing it immediately into the array
function addPersonImmediately(string memory _name, uint _age) public {
people.push(Person(_name, _age));
}
// Updating the array by modifying an existing struct
function updatePerson(uint _index, string memory _name, uint _age) public {
require(_index < people.length, "Invalid index");
Person storage person = people[_index];
person.name = _name;
person.age = _age;
}
// Modifying the array directly by index
function modifyPerson(uint _index, string memory _newName) public {
require(_index < people.length, "Invalid index");
people[_index].name = _newName;
}
// Deleting a struct in the array to reset it
function deletePerson(uint _index) public {
require(_index < people.length, "Invalid index");
// Move the last element to the deleted element's position
people[_index] = people[people.length - 1];
// Remove the last element (pop)
people.pop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment