That won't work when `Foo` has multiple fields of different types, since `v` 
might not be the correct type. Something like this works however: 
    
    
    type
      Foo = object
        field: int
        str: string
    
    proc `[]`(x: Foo, s: string, T: type): T =
      for n, v in x.fieldPairs:
        if n == s:
          when v is T:
            return v
          else:
            raiseAssert "Field has wrong type"
      raiseAssert "Field does not exist"
    
    var foo = Foo(field: 123, str: "abc")
    echo foo["field", int]
    echo foo["str", string]
    
    
    Run

Reply via email to