0

Is there a way to access variables in solidity using another variable?

Something like this:

contract Test {
    uint age;
    string varAge = "age";

    function setAge() public {
        // varAge should be able to access age variable
       ${varAge} = 30;
    }
}
1
  • Could you elaborate on your use case ?
    – hroussille
    Commented Apr 26, 2022 at 13:15

1 Answer 1

0

You can use a mapping to access through a specific key and modify its value. Example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {
    uint age;
    string varAge = "age";
    // Map string key with relative value
    mapping(string=>uint) mapAges;

    // Setter age
    function setAge() public {
        mapAges[varAge] = 30;
    }

    // Getter age
    function getAge() external view returns(uint) {
        return mapAges[varAge];
    }

} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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