1

I am new to solidity and just started exploring smart contracts.

I have a smart contract for creating a Person struct with name and age and a function to access the structs using the name variable:

contract SimpleStorage {
    struct Person {
        string name;
        int age;
    }
    
    mapping(string => Person) private nameLookup;

    function addPerson(string memory name, int age) public {
        nameLookup[name] = Person(name, age);
    }

    function getPerson(string memory name) public view returns(Person memory ret) {
        ret = nameLookup[name];
    }   
}

In another contract I have a StorageFactory which deploys a number of SimpleStorage contracts and wraps its functions:

contract StorageFactory {
    SimpleStorage[] public storages;

    function createSimpleStorageContract() public {
        SimpleStorage simpleStorage = new SimpleStorage();
        storages.push(simpleStorage);
    }

    function addPersonAt(uint256 index, string memory name, int age) public {
        SimpleStorage(address(storages[index])).addPerson(name, age);
    }

    function getPersonFrom(uint256 index, string memory name) public view returns(SimpleStorage.Person memory ret) {
        ret = SimpleStorage(address(storages[index])).getPerson(name);
    }
}

In the tutorial I am following they access the smart contract by passing the address of the contract stored in the storages array to a SimpleStorage constructor.

What is the difference between accessing the smart contract like this and just using the value stored in the array e.g:

SimpleStorage myStorage = storages[_index];

P.S: I tried both ways and they both seem to work. I could not find any information in the documentation or anywhere else. Any insight will be appreciated!

1 Answer 1

1

It's the same thing, except that the casting part is done implicitly in the second example you provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.