Variables
A variable in Julia is a name associated with (or bound to) a value. It is advisable to use it when you want to save a value (obtained, for example, after mathematical calculations) for later use. For example:
# Присваиваем значение 10 переменной x
julia> x = 10
10
# Выполняем вычисления со значением x
julia> x + 1
11
# Переприсваиваем значение x
julia> x = 1 + 1
2
# Вы можете присваивать значения других типов, например текстовые строки
julia> x = "Hello World!"
"Hello World!"
Julia provides an extremely flexible variable naming system. Variable names are case-sensitive and have no semantic meaning (that is, the language will not treat variables differently based on their names).
julia> x = 1.0
1.0
julia> y = -3
-3
julia> Z = "My string"
"My string"
julia> customary_phrase = "Hello world!"
"Hello world!"
julia> UniversalDeclarationOfHumanRightsStart = "人人生而自由,在尊严和权利上一律平等。"
"人人生而自由,在尊严和权利上一律平等。"
Unicode names (in UTF-8 encoding) are allowed.
julia> δ = 0.00001
1.0e-5
julia> 안녕하세요 = "Hello"
"Hello"
In REPL Julia and some other Julia editing environments, you can enter many mathematical Unicode characters by typing the name of a LaTeX character preceded by a backslash followed by a tab character. For example, you can enter the variable name δ
by typing \delta
-tab, or even α⁽2⁾
by typing \alpha
-tab-\hat
-tab-\^(2)
- tab. (If you have found a character somewhere, for example in someone else’s code, and do not know how to enter it, refer to the REPL help: just type ?
, and then insert the character.)
In Julia, you can even shade existing exported constants and functions with local ones (although this is not recommended to avoid possible confusion).
julia> pi = 3
3
julia> pi
3
julia> sqrt = 4
4
julia> length() = 5
length (generic function with 1 method)
julia> Base.length
length (generic function with 79 methods)
However, if you try to redefine a built-in constant or function that is already in use, Julia will give an error.
julia> pi
π = 3.1415926535897...
julia> pi = 3
ERROR: cannot assign a value to imported variable Base.pi from module Main
julia> sqrt(100)
10.0
julia> sqrt = 4
ERROR: cannot assign a value to imported variable Base.sqrt from module Main
Allowed variable names
Variable names must begin with a letter (A—Z or a—z), an underscore, or a subset of Unicode character codes greater than 00A0, in particular https://www.fileformat.info/info/unicode/category/index.htm [Unicode character categories] Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols). In addition, some other letter-like symbols are allowed (for example, a subset of the mathematical symbols Sm). Subsequent characters may also include ! and numbers (0-9 and other symbols of the Nd/No categories), as well as other Unicode character codes: diacritics and other modifying symbols (Mn/Mc/Me/Sk categories), some punctuation connectors (Pc category), strokes and other symbols.
Operators like +
are also valid identifiers, but they are analyzed in a special way. In some contexts, operators can be used in the same way as variables. For example, (+)
is used for the addition function, and (+) = f
will rewrite it. Most Unicode infix operators (in the Sm category), such as ⊕
, are analyzed as infix operators and are available for user-defined methods (for example, const ⊗ = kron
can be used to define ⊗
as an infix Kronecker product). Operators can also have a suffix with modifying characters, strokes, subscripts or superscripts. For example, +ₐ"
is analyzed as an infix operator with the same priority as +
. A space is required between an operator ending with a lowercase or uppercase letter and the subsequent variable name. For example, if +ᵃ
is an operator, then +ᵃx
should be written as +ᵃ x
to distinguish it from + ᵃx
, where ᵃx
is the variable name.
A special class of variable names is the one that contains only underscores. These IDs are writable only. That is, they can only be assigned values that are immediately deleted, and therefore cannot be used in any way.
julia> x, ___ = size([2 2; 1 1])
(2, 2)
julia> y = ___
ERROR: syntax: all-underscore identifiers are write-only and their values cannot be used in expressions
julia> println(___)
ERROR: syntax: all-underscore identifiers are write-only and their values cannot be used in expressions
The only explicitly forbidden names for variables are the names of the built-in ones. keywords.
julia> else = false
ERROR: syntax: unexpected "else"
julia> try = "No"
ERROR: syntax: unexpected "="
Some Unicode characters are considered equivalent in identifiers. Various ways of entering combined Unicode characters (for example, accents) are considered equivalent (in particular, Julia identifiers are https://en.wikipedia.org/wiki/Unicode_equivalence [NFC]). Julia also contains several non-standard equivalents for characters that are visually similar and easy to type using some input methods. The Unicode characters ɛ
(U+025B: Latin small letter open e) and µ
(U+00B5: micro sign) are considered equivalent to the corresponding Greek letters. The middle point is ·
(U+00B7) and Greek https://en.wikipedia.org/wiki/Interpunct [interpunct] ·
(U+0387) is considered as the mathematical operator "dot" ⋅
(U+22C5). The minus sign −
(U+2212) is considered the equivalent of the hyphen-minus sign -
(U+002D).
Assignment expressions and assignment-to-change comparison
When assigning variable = value
, the name variable
is "bound" to the calculated value of value
in the right part, and the entire assignment is considered in Julia as an expression equal to the value of value' in the right part. This means that assignments can be combined into chains (assign the same value to several variables in the form of `variable1 = variable2 = value') or used in other expressions. For the same reason, their results are displayed in the REPL as the values from the right side. (Usually, the value of the evaluated expression is displayed in the REPL.) For example, in this case, the value `4
of the expression b = 2+2
is used in another arithmetic operation and assignment.:
julia> a = (b = 2+2) + 3
7
julia> a
7
julia> b
4
The concepts of assignment (that is, assigning a new "name" to a value) and value change are often confused. If you run a = 2
and then a = 3
, the name
of a' will refer to the new value '3'. The number `2
has not changed, so 2+2
will be equal to 4
, not `6'! This difference becomes more apparent when working with change_types such as arrays whose contents can be changed:
julia> a = [1,2,3] # массив из 3 целых чисел
3-element Vector{Int64}:
1
2
3
julia> b = a # b и a — это имена одного и того же массива!
3-element Vector{Int64}:
1
2
3
In this case, the string b = a
does not cause the array a
to be copied. The name b
simply binds to the fourth array a
: both b
and a
"point" to a single array [1,2,3]
in memory. On the contrary, assigning a[i] = value
_ changes the contents of the array, so that the modified array will be available by the names a
and b
:
julia> a[1] = 42 # изменяем первый элемент
42
julia> a = 3.14159 # a теперь является именем другого объекта
3.14159
julia> b # b ссылается на исходный объект массива, который был изменен
3-element Vector{Int64}:
42
2
3
Thus, a[i] = value
(an alias for 'setindex!) _ modifies an existing array object in memory, accessible by the name `a or
b'. If you subsequently set `a = 3.14159
, the array will not change, but instead the name a
will simply be reassigned to another object; the array will still be accessible by the name b
. Another common syntactic construct for modifying an existing object is a.field = value
(an alias for setproperty!
). You can use it to change the mutable structure (mutable struct
). There is also a change via assignment with a dot, for example b'.= 5:7
(which modifies our array b
in place so that it contains [5,6,7]
) as part of vector syntax with a dot Julia.
When calling functions in Julia, you sort of assign argument values to new variable names corresponding to function arguments, as described in Behavior when passing arguments. (According to by convention the names of functions that change one or more of their arguments end with the character !
.)
Stylistic conventions
Although Julia imposes few restrictions on acceptable names, it is recommended that the following standards be followed.
-
Variable names are indicated in lowercase.
-
The division of words can be indicated by underscores ( ), but it is not recommended to use underscores, otherwise the name will be difficult to read.
-
The names of types (
Type
) and modules (Module
) begin with a capital letter, and the camel style is used to separate words, not underscores. -
The names of functions (
function
) and macros (macro
) are indicated in lowercase without underscores. -
The names of the functions that they write to their arguments end in
!
. They are sometimes called mutable or internal, because they are designed to make changes to their arguments after calling a function, rather than simply returning a value.
For more information about stylistic conventions, see style guide.