mirror of
https://github.com/nim-lang/Nim.git
synced 2026-01-01 10:52:14 +00:00
58 lines
1.8 KiB
Plaintext
58 lines
1.8 KiB
Plaintext
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)
|
|
|
|
|