Hi all, just a bit of an update. I was exploring and messing around with the code. Like @cryptozz, I found that in Filipās example of using the mapping ownerToDog[owner] = id;, if the same owner, or address input, has more than 1 dog, only the latest dog id will be retrieved.
I spent some time thinking about how can I possibly retrieve an earlier dog. Of course, we could simply do the following:
function getDog(uint _arrayIndex) returns (string){
return dogs[_arrayIndex].name;
}
But that way, any address can retrieve another addressās array elements. So Iāve tried to combine the function above with the mapping function, and tested it in the following code:
pragma solidity ^0.4.24;
contract People{
mapping (address => uint) personLocation;
struct Person{
string name;
uint age;
string occupation;
}
Person[] people;
function addPerson(string _name, uint _age, string _occupation){
address location = msg.sender;
uint id = people.push(Person(_name, _age, _occupation));
personLocation[location] = id;
}
function getName(uint _index) returns(string){
address location = msg.sender;
uint id = personLocation[location];
return people[id - _index].name;
}
function getAge(uint _index) returns (uint){
address location = msg.sender;
uint id = personLocation[location];
return people[id - _index].age;
}
function getOccupation(uint _index) returns (string){
address location = msg.sender;
uint id = personLocation[location];
return people[id - _index].occupation;
}
This way, I had success in accessing different elements within an array of a single address, and other addresses give an error when I tried to access it. Only problem now is that the argument that I put into each function, _index, is now āreversedā. When I input _index as 2, it will access the second last element. Not very intuitive, but I havenāt been able to find an alternative. My first time learn code is through this course, so I clearly have a long way to go. If anyone has a better solution, please teach me!
This was pretty interesting, and I learned a little more on why other addresses could not access the data of another address. Basically, when we run the line
uint id = personLocation[location];
If the address is not the sender of the contract, id is automatically zero. So in Filipās example, when we try to retrieve
dogs[id -1].name;
We are trying to retrieve element -1, which is invalid, returning an error. Hope it isnāt too long winded, and that it might help someone better understand what is going on!