2

Can we access the struct member using a variable as we access in JavaScript? For example:

struct Abc {
     uint256 a,
     uint256 b
}

Abc xyz;

string memName = 'a';

I want to do something like this:

xyz[memName] 

as we can do in JavaScript.

1 Answer 1

1

To my knowledge, the only way to access a struct member is by calling its name after the dot notation. As for your example:

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

contract Test {

   struct Abc {
     uint256 a;
     uint256 b;
   }

   Abc xyz;

   string memName = 'a';

   function set() external {
     xyz = Abc(5,10);
   }

   function get() external view returns(uint256) {
     return xyz.a;
   }
}

You will get an error if you try to access a struct member through any of the following methods:

    return xyz[memName];
    return xyz['a'];

The error message is quite explicit:

TypeError: Indexed expression has to be a type, mapping or array

Which means that notation xyz[whatever] is only reserved to types, mappings or arrays, but not structs. Therefore, unless you know in advance the name member of the struct, you won't be able to access it through a variable.

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.