mirror of
https://github.com/nim-lang/Nim.git
synced 2026-06-04 10:54:42 +00:00
Merge pull request #2998 from apense/patch-4
Added `$` documentation to the manual
This commit is contained in:
@@ -342,6 +342,34 @@ builtin ``len`` procedure; the length never counts the terminating zero.
|
||||
The assignment operator for strings always copies the string.
|
||||
The ``&`` operator concatenates strings.
|
||||
|
||||
Most native Nim types support conversion to strings with the special ``$`` proc.
|
||||
When calling the ``echo`` proc, for example, the built-in stringify operation
|
||||
for the parameter is called:
|
||||
|
||||
.. code-block:: nim
|
||||
|
||||
echo 3 # calls `$` for `int`
|
||||
|
||||
Whenever a user creates a specialized object, implementation of this procedure
|
||||
provides for ``string`` representation.
|
||||
|
||||
.. code-block:: nim
|
||||
type
|
||||
Person = object
|
||||
name: string
|
||||
age: int
|
||||
|
||||
proc `$`(p: Person): string = # `$` always returns a string
|
||||
result = p.name & " is " &
|
||||
$p.age & # we *need* the `$` in front of p.age, which
|
||||
# is natively an integer, to convert it to
|
||||
# a string
|
||||
" years old."
|
||||
|
||||
While ``$p.name`` can also be used, the ``$`` operation on a string does
|
||||
nothing. Note that we cannot rely on automatic conversion from an ``int`` to
|
||||
a ``string`` like we can for the ``echo`` proc.
|
||||
|
||||
Strings are compared by their lexicographical order. All comparison operators
|
||||
are available. Strings can be indexed like arrays (lower bound is 0). Unlike
|
||||
arrays, they can be used in case statements:
|
||||
|
||||
Reference in New Issue
Block a user