If the user calls this function multiple times, multiple dogs will be created and stored in the dogs
array. But the reference id
will be overwritten. So your ownerToDog
mapping will only point to the latest Dog
in the dogs
array, and all other instances will be stored indefinitely.
There’s many solutions, depending on what kind of data you want to collect. For example, I like arrays for getting total counts of dogs
, something you can’t do with a struct.
Presuming your users can only have one dog, like it seems like you want? My solution would look like this;
pragma solidity ^0.4.22; // Revision 22 allows require to emit messages
contract DogContract {
struct Dog {
string name = "";
uint age = 0;
}
mapping(address => Dog) ownerToDog;
event addedDog(address owner, string name);
function addDog(string _name, uint _age) public {
// Generate hash (no owner can have two identical named dogs)
bytes32 dogHash = keccak256(msg.sender, _name);
// Ensure dog doesn't exist
require(ownerToDog[msg.sender].name != "", "You already own a dog");
// Create our dog
ownerToDog[Dog(_name, _age)];
// Notify
emit addedDog(owner, _name, id);
}
function getDog(string _name) returns (string) {
string dogName = ownerToDog[msg.sender];
require(dogName != "", "You don't own a dog");
return dogName;
}
}
Limitations:
- User can only have one dog (You could make a transfer function)
- Can’t count total dogs
- Probably more, this is fairly limited