-2

I am new to rust with a javaScript background and i am stuck with getting a value of a json key dynamically.

In JS if i have an object = { "xyz" : "one" , "jkl" : "two" }; and if i have a variable name = "xyz"; , then i can find the corresponding value of 'xyz' key in the object using object[name] which will give me "one" as a result.

Now i have the exact same flow in rust, where i have

let obj = config.clone();     // because config is struct (only cloning could remove the error)
let name = "xyz";             // A variable which is a key in the object
let result = obj[name];`      // result which is giving me "cannot index into a value of type `Configuration`" error 

I am aware that creating a dict or hashmap will exponentially reduce the time, but the object i have can contain upto 1000 keys and values or more.

If i can create a hashmap with the object I already have, that would be a relief ( only if i knew ).

I have tried multiple ways by just googling a bunch of stuff

  1. let result = obj[name];
  2. let result = obj.&name];
  3. let result = obj[$name];
  4. let result = obj[&name];
  5. let result = obj.$name;

none of them seems to solve the issue.

Thanks in advance.

user2722968
  • 13,636
  • 2
  • 46
  • 67
Lakshay Kalra
  • 317
  • 3
  • 14

1 Answers1

0

Accessing fields of structs dynamically is not possible out of the box. See this earlier question.

Sander Bollen
  • 627
  • 5
  • 7