Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Solution to Introduction to Solidity Scenario Example
pragma solidity ^0.4.20;
contract Cars {
// we declare a custom type car
struct Car {
bytes32 make;
uint year;
// we create a map that takes ethereum address and maps them to a Cars array
mapping(address => Car[]) public carOwners;
function registerCar(bytes32 _make, uint yr) public {
// assign new struct
// assign the car
make: _make,
year: yr
// change car ownership by providing owner and index
function changeOwnership(address toOwner, uint index) public returns (bool) {
// check if sender has cars
// can be refactored to a function modifier
if (carOwners[msg.sender].length == 0) {
return false;
if (carOwners[msg.sender].length > index+1) {
return false;
// TODO: remove the car from the current owner, otherwise there's a duplicate.
// get a car by providing owner and index
function getCarMake(address owner, uint index) public view returns (bytes32 carMake) {
if (carOwners[owner].length == 0 ){
if (carOwners[owner].length > index+1) {
carMake = carOwners[owner][index].make;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.