12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- Special Operators
- =================
- dot operators
- -------------
- **Note**: Dot operators are still experimental and so need to be enabled
- via ``{.experimental.}``.
- Nim offers a special family of dot operators that can be used to
- intercept and rewrite proc call and field access attempts, referring
- to previously undeclared symbol names. They can be used to provide a
- fluent interface to objects lying outside the static confines of the
- type system such as values from dynamic scripting languages
- or dynamic file formats such as JSON or XML.
- When Nim encounters an expression that cannot be resolved by the
- standard overload resolution rules, the current scope will be searched
- for a dot operator that can be matched against a re-written form of
- the expression, where the unknown field or proc name is converted to
- an additional static string parameter:
- .. code-block:: nim
- a.b # becomes `.`(a, "b")
- a.b(c, d) # becomes `.`(a, "b", c, d)
- The matched dot operators can be symbols of any callable kind (procs,
- templates and macros), depending on the desired effect:
- .. code-block:: nim
- proc `.` (js: PJsonNode, field: string): JSON = js[field]
- var js = parseJson("{ x: 1, y: 2}")
- echo js.x # outputs 1
- echo js.y # outputs 2
- The following dot operators are available:
- operator `.`
- ------------
- This operator will be matched against both field accesses and method calls.
- operator `.()`
- ---------------
- This operator will be matched exclusively against method calls. It has higher
- precedence than the `.` operator and this allows one to handle expressions like
- `x.y` and `x.y()` differently if one is interfacing with a scripting language
- for example.
- operator `.=`
- -------------
- This operator will be matched against assignments to missing fields.
- .. code-block:: nim
- a.b = c # becomes `.=`(a, "b", c)
|