Julia 中,變量即是關聯到某個值的名字。當你想存儲一個值(比如數學計算中的某個中間變量)以備后用時,變量的作用就體現出來了。舉個例子:
```
# Assign the value 10 to the variable x
julia> x = 10
10
# Doing math with x's value
julia> x + 1
11
# Reassign x's value
julia> x = 1 + 1
2
# You can assign values of other types, like strings of text
julia> x = "Hello World!"
"Hello World!"
```
Julia 提供了極其靈活的變量命名系統。變量名區分大小寫。
```
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 字符(UTF-8 編碼)來命名:
```
julia> δ = 0.00001
1.0e-5
julia> ????? = "Hello"
"Hello"
```
在 Julia REPL 和其它一些 Julia 的編輯環境中,支持 Unicode 數學符號 的輸入。只需要鍵入對應的 LaTeX 語句,再按 tab 鍵即可完成輸入。 比如,變量名 `δ` 可以通過 `\delta-tab` 來輸入,又如 ``α??` `` 可以由` ``\alpha-tab-\hat-tab-\_2-tab` 來完成。
Julia 甚至允許重新定義內置的常數和函數:
```
julia> pi
π = 3.1415926535897...
julia> pi = 3
Warning: imported binding for pi overwritten in module Main
3
julia> pi
3
julia> sqrt(100)
10.0
julia> sqrt = 4
Warning: imported binding for sqrt overwritten in module Main
4
```
很顯然, 不鼓勵這樣的做法。
可用的變量名
Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0; in particular, [Unicode character categories](http://www.fileformat.info/info/unicode/category/index.htm) Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols), and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points: diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes, and a few other characters.
Operators like `+` are also valid identifiers, but are parsed specially. In some contexts, operators can be used just like variables; for example` (+)` refers to the addition function, and `(+) = f` will reassign it. Most of the Unicode infix operators (in category Sm), such as` ⊕,` are parsed as infix operators and are available for user-defined methods (e.g. you can use `const ? = kron` to define` ?` as an infix Kronecker product).
內置的關鍵字不能當變量名:
```
julia> else = false
ERROR: syntax: unexpected "else"
julia> try = "No"
ERROR: syntax: unexpected "="
```
命名規范
盡管 Julia 對命名本身只有很少的限制, 但盡量遵循一定的命名規范吧:
* 變量名使用小寫字母
* 單詞間使用下劃線 ('_') 分隔,但不鼓勵
* 類型名首字母大寫, 單詞間使用駝峰式分隔.
* 函數名和宏名使用小寫字母, 不使用下劃線分隔單詞.
*修改參數的函數結尾使用 ! . 這樣的函數被稱為 mutating functions 或 in-place functions