diff options
author | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2013-11-26 13:34:54 +0100 |
---|---|---|
committer | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2013-11-26 13:34:54 +0100 |
commit | 0a953de3a819de8d0a14943054427924f31ff05e (patch) | |
tree | a6e1ff687ac698f1c2de149ac14bea487819441d /doc | |
parent | e469bdb6faae28514388cc4190c04373eb4b8dea (diff) | |
download | Nim-0a953de3a819de8d0a14943054427924f31ff05e.tar.gz |
Adds to tutorial info about unpacking tuples.
Diffstat (limited to 'doc')
-rw-r--r-- | doc/tut1.txt | 40 |
1 files changed, 37 insertions, 3 deletions
diff --git a/doc/tut1.txt b/doc/tut1.txt index 5c1cdb52e..b46fb2c68 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -189,9 +189,18 @@ to a storage location: var x = "abc" # introduces a new variable `x` and assigns a value to it x = "xyz" # assigns a new value to `x` -``=`` is the *assignment operator*. The assignment operator cannot -be overloaded, overwritten or forbidden, but this might change in a future -version of Nimrod. +``=`` is the *assignment operator*. The assignment operator cannot be +overloaded, overwritten or forbidden, but this might change in a future version +of Nimrod. You can declare multiple variables with a single assignment +statement and all the variables will have the same value: + +.. code-block:: + var x, y = 3 # assigns 3 to the variables `x` and `y` + echo "x ", x # outputs "x 3" + echo "y ", y # outputs "y 3" + x = 42 # changes `x` to 42 without changing `y` + echo "x ", x # outputs "x 42" + echo "y ", y # outputs "y 3" Constants @@ -1352,6 +1361,31 @@ Even though you don't need to declare a type for a tuple to use it, tuples created with different field names will be considered different objects despite having the same field types. +Tuples can be *unpacked* during variable assignment. This can be handy to +assign directly the fields of the tuples to individually named variables. An +example of this is the ``splitFile`` proc from the `os module <os.html>`_ which +returns the directory, name and extension of a path at the same time. For tuple +unpacking to work you have to use parenthesis around the values you want to +assign the unpacking to, otherwise you will be assigning the same value to all +the individual variables! Example: + +.. code-block:: nimrod + + import os + + let + path = "usr/local/nimrodc.html" + (dir, name, ext) = splitFile(path) + baddir, badname, badext = splitFile(path) + echo dir # outputs `usr/local` + echo name # outputs `nimrodc` + echo ext # outputs `.html` + # All the following output the same line: + # `(dir: usr/local, name: nimrodc, ext: .html)` + echo baddir + echo badname + echo badext + Reference and pointer types --------------------------- |