### [What are the possible causes of an UndefVarError during remote execution?](#What-are-the-possible-causes-of-an-UndefVarError-during-remote-execution?)
As the error states, an immediate cause of an `UndefVarError` on a remote node is that a binding by that name does not exist. Let us explore some of the possible causes.
```julia-repl
julia> module Foo
           foo() = remotecall_fetch(x->x, 2, "Hello")
       end

julia> Foo.foo()
ERROR: On worker 2:
UndefVarError: `Foo` not defined in `Main`
Stacktrace:
[...]
```
The closure `x->x` carries a reference to `Foo`, and since `Foo` is unavailable on node 2, an `UndefVarError` is thrown.
Globals under modules other than `Main` are not serialized by value to the remote node. Only a reference is sent. Functions which create global bindings (except under `Main`) may cause an `UndefVarError` to be thrown later.
```julia-repl
julia> @everywhere module Foo
           function foo()
               global gvar = "Hello"
               remotecall_fetch(()->gvar, 2)
           end
       end

julia> Foo.foo()
ERROR: On worker 2:
UndefVarError: `gvar` not defined in `Main.Foo`
Stacktrace:
[...]
```
In the above example, `@everywhere module Foo` defined `Foo` on all nodes. However the call to `Foo.foo()` created a new global binding `gvar` on the local node, but this was not found on node 2 resulting in an `UndefVarError` error.
Note that this does not apply to globals created under module `Main`. Globals under module `Main` are serialized and new bindings created under `Main` on the remote node.


### [What are the possible causes of an UndefVarError during remote execution?](#What-are-the-possible-causes-of-an-UndefVarError-during-remote-execution?)
```julia-repl
julia> gvar_self = "Node1"
"Node1"

julia> remotecall_fetch(()->gvar_self, 2)
"Node1"

julia> remotecall_fetch(varinfo, 2)
name          size summary
––––––––– –––––––– –––––––
Base               Module
Core               Module
Main               Module
gvar_self 13 bytes String
```
This does not apply to `function` or `struct` declarations. However, anonymous functions bound to global variables are serialized as can be seen below.
```julia-repl
julia> bar() = 1
bar (generic function with 1 method)

julia> remotecall_fetch(bar, 2)
ERROR: On worker 2:
UndefVarError: `#bar` not defined in `Main`
[...]

julia> anon_bar  = ()->1
(::#21) (generic function with 1 method)

julia> remotecall_fetch(anon_bar, 2)
1
```


## [Troubleshooting "method not matched": parametric type invariance and MethodErrors](#Troubleshooting-%22method-not-matched%22:-parametric-type-invariance-and-MethodErrors)


### [Why doesn't it work to declare foo(bar::Vector{Real}) = 42 and then call foo([1\])?](#Why-doesn't-it-work-to-declare-foo(bar::Vector%7BReal%7D)-42-and-then-call-foo(%5B1%5D)?)
As you'll see if you try this, the result is a `MethodError`:
```julia-repl
julia> foo(x::Vector{Real}) = 42
foo (generic function with 1 method)

julia> foo([1])
ERROR: MethodError: no method matching foo(::Vector{Int64})
The function `foo` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  foo(!Matched::Vector{Real})
   @ Main none:1

Stacktrace:
[...]
```
This is because `Vector{Real}` is not a supertype of `Vector{Int}`! You can solve this problem with something like `foo(bar::Vector{T}) where {T<:Real}` (or the short form `foo(bar::Vector{<:Real})` if the static parameter `T` is not needed in the body of the function). The `T` is a wild card: you first specify that it must be a subtype of Real, then specify the function takes a Vector of with elements of that type.
This same issue goes for any composite type `Comp`, not just `Vector`. If `Comp` has a parameter declared of type `Y`, then another type `Comp2` with a parameter of type `X<:Y` is not a subtype of `Comp`. This is type-invariance (by contrast, Tuple is type-covariant in its parameters). See [Parametric Composite Types](../types/#man-parametric-composite-types) for more explanation of these.


### [Why does Julia use * for string concatenation? Why not + or something else?](#Why-does-Julia-use-*-for-string-concatenation?-Why-not-or-something-else?)
The [main argument](../strings/#man-concatenation) against `+` is that string concatenation is not commutative, while `+` is generally used as a commutative operator. While the Julia community recognizes that other languages use different operators and `*` may be unfamiliar for some users, it communicates certain algebraic properties.
Note that you can also use `string(...)` to concatenate strings (and other values converted to strings); similarly, `repeat` can be used instead of `^` to repeat strings. The [interpolation syntax](../strings/#string-interpolation) is also useful for constructing strings.


## [Packages and Modules](#Packages-and-Modules)


### [What is the difference between "using" and "import"?](#What-is-the-difference-between-%22using%22-and-%22import%22?)
There are several differences between `using` and `import` (see the [Modules section](https://docs.julialang.org/en/v1/manual/modules/#modules)), but there is an important difference that may not seem intuitive at first glance, and on the surface (i.e. syntax-wise) it may seem very minor. When loading modules with `using`, you need to say `function Foo.bar(...` to extend module `Foo`'s function `bar` with a new method, but with `import Foo.bar`, you only need to say `function bar(...` and it automatically extends module `Foo`'s function `bar`.
The reason this is important enough to have been given separate syntax is that you don't want to accidentally extend a function that you didn't know existed, because that could easily cause a bug. This is most likely to happen with a method that takes a common type like a string or integer, because both you and the other module could define a method to handle such a common type. If you use `import`, then you'll replace the other module's implementation of `bar(s::AbstractString)` with your new implementation, which could easily do something completely different (and break all/many future usages of the other functions in module Foo that depend on calling bar).


## [Nothingness and missing values](#Nothingness-and-missing-values)


### [How does "null", "nothingness" or "missingness" work in Julia?](#faq-nothing)
Unlike many languages (for example, C and Java), Julia objects cannot be "null" by default. When a reference (variable, object field, or array element) is uninitialized, accessing it will immediately throw an error. This situation can be detected using the [`isdefined`](../../base/base/#Core.isdefined) or [`isassigned`](../../base/arrays/#Base.isassigned) functions.
Some functions are used only for their side effects, and do not need to return a value. In these cases, the convention is to return the value `nothing`, which is just a singleton object of type `Nothing`. This is an ordinary type with no fields; there is nothing special about it except for this convention, and that the REPL does not print anything for it. Some language constructs that would not otherwise have a value also yield `nothing`, for example `if false; end`.


### [How does "null", "nothingness" or "missingness" work in Julia?](#faq-nothing)
For situations where a value `x` of type `T` exists only sometimes, the `Union{T, Nothing}` type can be used for function arguments, object fields and array element types as the equivalent of [`Nullable`, `Option` or `Maybe`](https://en.wikipedia.org/wiki/Nullable_type) in other languages. If the value itself can be `nothing` (notably, when `T` is `Any`), the `Union{Some{T}, Nothing}` type is more appropriate since `x == nothing` then indicates the absence of a value, and `x == Some(nothing)` indicates the presence of a value equal to `nothing`. The [`something`](../../base/base/#Base.something) function allows unwrapping `Some` objects and using a default value instead of `nothing` arguments. Note that the compiler is able to generate efficient code when working with `Union{T, Nothing}` arguments or fields.
To represent missing data in the statistical sense (`NA` in R or `NULL` in SQL), use the [`missing`](../missing/#missing) object. See the [`Missing Values`](../missing/#missing) section for more details.
In some languages, the empty tuple (`()`) is considered the canonical form of nothingness. However, in julia it is best thought of as just a regular tuple that happens to contain zero values.
The empty (or "bottom") type, written as `Union{}` (an empty union type), is a type with no values and no subtypes (except itself). You will generally not need to use this type.


## [Memory](#Memory)


### [Why does x += y allocate memory when x and y are arrays?](#Why-does-x-y-allocate-memory-when-x-and-y-are-arrays?)
In Julia, `x += y` gets replaced during lowering by `x = x + y`. For arrays, this has the consequence that, rather than storing the result in the same location in memory as `x`, it allocates a new array to store the result. If you prefer to mutate `x`, use `x .+= y` to update each element individually.
While this behavior might surprise some, the choice is deliberate. The main reason is the presence of immutable objects within Julia, which cannot change their value once created. Indeed, a number is an immutable object; the statements `x = 5; x += 1` do not modify the meaning of `5`, they modify the value bound to `x`. For an immutable, the only way to change the value is to reassign it.
To amplify a bit further, consider the following function:
```julia
function power_by_squaring(x, n::Int)
    ispow2(n) || error("This implementation only works for powers of 2")
    while n >= 2
        x *= x
        n >>= 1
    end
    x
end
```
After a call like `x = 5; y = power_by_squaring(x, 4)`, you would get the expected result: `x == 5 && y == 625`. However, now suppose that `*=`, when used with matrices, instead mutated the left hand side. There would be two problems:
-   For general square matrices, `A = A*B` cannot be implemented without temporary storage: `A[1,1]` gets computed and stored on the left hand side before you're done using it on the right hand side.


### [Why does x += y allocate memory when x and y are arrays?](#Why-does-x-y-allocate-memory-when-x-and-y-are-arrays?)
-   Suppose you were willing to allocate a temporary for the computation (which would eliminate most of the point of making `*=` work in-place); if you took advantage of the mutability of `x`, then this function would behave differently for mutable vs. immutable inputs. In particular, for immutable `x`, after the call you'd have (in general) `y != x`, but for mutable `x` you'd have `y == x`.
Because supporting generic programming is deemed more important than potential performance optimizations that can be achieved by other means (e.g., using broadcasting or explicit loops), operators like `+=` and `*=` work by rebinding new values.


## [Asynchronous IO and concurrent synchronous writes](#faq-async-io)


### [Why do concurrent writes to the same stream result in inter-mixed output?](#Why-do-concurrent-writes-to-the-same-stream-result-in-inter-mixed-output?)
While the streaming I/O API is synchronous, the underlying implementation is fully asynchronous.
Consider the printed output from the following:
```julia-repl
julia> @sync for i in 1:3
           @async write(stdout, string(i), " Foo ", " Bar ")
       end
123 Foo  Foo  Foo  Bar  Bar  Bar
```
This is happening because, while the `write` call is synchronous, the writing of each argument yields to other tasks while waiting for that part of the I/O to complete.
`print` and `println` "lock" the stream during a call. Consequently changing `write` to `println` in the above example results in:
```julia-repl
julia> @sync for i in 1:3
           @async println(stdout, string(i), " Foo ", " Bar ")
       end
1 Foo  Bar
2 Foo  Bar
3 Foo  Bar
```
You can lock your writes with a `ReentrantLock` like this:
```julia-repl
julia> l = ReentrantLock();

julia> @sync for i in 1:3
           @async begin
               lock(l)
               try
                   write(stdout, string(i), " Foo ", " Bar ")
               finally
                   unlock(l)
               end
           end
       end
1 Foo  Bar 2 Foo  Bar 3 Foo  Bar
```


## [Arrays](#Arrays)


### [What are the differences between zero-dimensional arrays and scalars?](#faq-array-0dim)
Zero-dimensional arrays are arrays of the form `Array{T,0}`. They behave similar to scalars, but there are important differences. They deserve a special mention because they are a special case which makes logical sense given the generic definition of arrays, but might be a bit unintuitive at first. The following line defines a zero-dimensional array:
```julia
julia> A = zeros()
0-dimensional Array{Float64,0}:
0.0
```
In this example, `A` is a mutable container that contains one element, which can be set by `A[] = 1.0` and retrieved with `A[]`. All zero-dimensional arrays have the same size (`size(A) == ()`), and length (`length(A) == 1`). In particular, zero-dimensional arrays are not empty. If you find this unintuitive, here are some ideas that might help to understand Julia's definition.
-   Zero-dimensional arrays are the "point" to vector's "line" and matrix's "plane". Just as a line has no area (but still represents a set of things), a point has no length or any dimensions at all (but still represents a thing).
-   We define `prod(())` to be 1, and the total number of elements in an array is the product of the size. The size of a zero-dimensional array is `()`, and therefore its length is `1`.


### [What are the differences between zero-dimensional arrays and scalars?](#faq-array-0dim)
-   Zero-dimensional arrays don't natively have any dimensions into which you index – they’re just `A[]`. We can apply the same "trailing one" rule for them as for all other array dimensionalities, so you can indeed index them as `A[1]`, `A[1,1]`, etc; see [Omitted and extra indices](../arrays/#Omitted-and-extra-indices).
It is also important to understand the differences to ordinary scalars. Scalars are not mutable containers (even though they are iterable and define things like `length`, `getindex`, *e.g.* `1[] == 1`). In particular, if `x = 0.0` is defined as a scalar, it is an error to attempt to change its value via `x[] = 1.0`. A scalar `x` can be converted into a zero-dimensional array containing it via `fill(x)`, and conversely, a zero-dimensional array `a` can be converted to the contained scalar via `a[]`. Another difference is that a scalar can participate in linear algebra operations such as `2 * rand(2,2)`, but the analogous operation with a zero-dimensional array `fill(2) * rand(2,2)` is an error.


### [Why are my Julia benchmarks for linear algebra operations different from other languages?](#Why-are-my-Julia-benchmarks-for-linear-algebra-operations-different-from-other-languages?)
You may find that simple benchmarks of linear algebra building blocks like
```julia
using BenchmarkTools
A = randn(1000, 1000)
B = randn(1000, 1000)
@btime $A \ $B
@btime $A * $B
```
can be different when compared to other languages like Matlab or R.
Since operations like this are very thin wrappers over the relevant BLAS functions, the reason for the discrepancy is very likely to be
1.  the BLAS library each language is using,
2.  the number of concurrent threads.
Julia compiles and uses its own copy of OpenBLAS, with threads currently capped at `8` (or the number of your cores).
Modifying OpenBLAS settings or compiling Julia with a different BLAS library, eg [Intel MKL](https://software.intel.com/en-us/mkl), may provide performance improvements. You can use [MKL.jl](https://github.com/JuliaComputing/MKL.jl), a package that makes Julia's linear algebra use Intel MKL BLAS and LAPACK instead of OpenBLAS, or search the discussion forum for suggestions on how to set this up manually. Note that Intel MKL cannot be bundled with Julia, as it is not open source.


## [Computing cluster](#Computing-cluster)


### [How do I manage precompilation caches in distributed file systems?](#How-do-I-manage-precompilation-caches-in-distributed-file-systems?)
When using Julia in high-performance computing (HPC) facilities with shared filesystems, it is recommended to use a shared depot (via the [`JULIA_DEPOT_PATH`](../environment-variables/#JULIA_DEPOT_PATH) environment variable). Since Julia v1.10, multiple Julia processes on functionally similar workers and using the same depot will coordinate via pidfile locks to only spend effort precompiling on one process while the others wait. The precompilation process will indicate when the process is precompiling or waiting for another that is precompiling. If non-interactive the messages are via `@debug`.
However, due to caching of binary code, the cache rejection since v1.9 is more strict and users may need to set the [`JULIA_CPU_TARGET`](../environment-variables/#JULIA_CPU_TARGET) environment variable appropriately to get a single cache that is usable throughout the HPC environment.


## [Julia Releases](#Julia-Releases)


### [Do I want to use the Stable, LTS, or nightly version of Julia?](#Do-I-want-to-use-the-Stable,-LTS,-or-nightly-version-of-Julia?)
The Stable version of Julia is the latest released version of Julia, this is the version most people will want to run. It has the latest features, including improved performance. The Stable version of Julia is versioned according to [SemVer](https://semver.org/) as v1.x.y. A new minor release of Julia corresponding to a new Stable version is made approximately every 4-5 months after a few weeks of testing as a release candidate. Unlike the LTS version the Stable version will not normally receive bugfixes after another Stable version of Julia has been released. However, upgrading to the next Stable release will always be possible as each release of Julia v1.x will continue to run code written for earlier versions.


### [Do I want to use the Stable, LTS, or nightly version of Julia?](#Do-I-want-to-use-the-Stable,-LTS,-or-nightly-version-of-Julia?)
You may prefer the LTS (Long Term Support) version of Julia if you are looking for a very stable code base. The current LTS version of Julia is versioned according to SemVer as v1.6.x; this branch will continue to receive bugfixes until a new LTS branch is chosen, at which point the v1.6.x series will no longer received regular bug fixes and all but the most conservative users will be advised to upgrade to the new LTS version series. As a package developer, you may prefer to develop for the LTS version, to maximize the number of users who can use your package. As per SemVer, code written for v1.0 will continue to work for all future LTS and Stable versions. In general, even if targeting the LTS, one can develop and run code in the latest Stable version, to take advantage of the improved performance; so long as one avoids using new features (such as added library functions or new methods).


### [Do I want to use the Stable, LTS, or nightly version of Julia?](#Do-I-want-to-use-the-Stable,-LTS,-or-nightly-version-of-Julia?)
You may prefer the nightly version of Julia if you want to take advantage of the latest updates to the language, and don't mind if the version available today occasionally doesn't actually work. As the name implies, releases to the nightly version are made roughly every night (depending on build infrastructure stability). In general nightly released are fairly safe to use—your code will not catch on fire. However, they may be occasional regressions and or issues that will not be found until more thorough pre-release testing. You may wish to test against the nightly version to ensure that such regressions that affect your use case are caught before a release is made.
Finally, you may also consider building Julia from source for yourself. This option is mainly for those individuals who are comfortable at the command line, or interested in learning. If this describes you, you may also be interested in reading our [guidelines for contributing](https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md).
The [`juliaup` install manager](https://julialang.org/install/) has pre-defined channels named `release` and `lts` for the latest stable release and the current LTS release, as well as version-specific channels.


### [How can I transfer the list of installed packages after updating my version of Julia?](#How-can-I-transfer-the-list-of-installed-packages-after-updating-my-version-of-Julia?)
Each minor version of julia has its own default [environment](https://docs.julialang.org/en/v1/manual/code-loading/#Environments-1). As a result, upon installing a new minor version of Julia, the packages you added using the previous minor version will not be available by default. The environment for a given julia version is defined by the files `Project.toml` and `Manifest.toml` in a folder matching the version number in `.julia/environments/`, for instance, `.julia/environments/v1.3`.
If you install a new minor version of Julia, say `1.4`, and want to use in its default environment the same packages as in a previous version (e.g. `1.3`), you can copy the contents of the file `Project.toml` from the `1.3` folder to `1.4`. Then, in a session of the new Julia version, enter the "package management mode" by typing the key `]`, and run the command [`instantiate`](https://julialang.github.io/Pkg.jl/v1/api/#Pkg.instantiate).


### [How can I transfer the list of installed packages after updating my version of Julia?](#How-can-I-transfer-the-list-of-installed-packages-after-updating-my-version-of-Julia?)
This operation will resolve a set of feasible packages from the copied file that are compatible with the target Julia version, and will install or update them if suitable. If you want to reproduce not only the set of packages, but also the versions you were using in the previous Julia version, you should also copy the `Manifest.toml` file before running the Pkg command `instantiate`. However, note that packages may define compatibility constraints that may be affected by changing the version of Julia, so the exact set of versions you had in `1.3` may not work for `1.4`.
------------------------------------------------------------------------


# Noteworthy Differences from other Languages · The Julia Language
Source: https://docs.julialang.org/en/v1/manual/noteworthy-differences/


# [Noteworthy Differences from other Languages](#Noteworthy-Differences-from-other-Languages)


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
Although MATLAB users may find Julia's syntax familiar, Julia is not a MATLAB clone. There are major syntactic and functional differences. The following are some noteworthy differences that may trip up Julia users accustomed to MATLAB:
-   Julia arrays are indexed with square brackets, `A[i,j]`.
-   Julia arrays are not copied when assigned to another variable. After `A = B`, changing elements of `B` will modify `A` as well. To avoid this, use `A = copy(B)`.
-   Julia values are not copied when passed to a function. If a function modifies an array, the changes will be visible in the caller.
-   Julia does not automatically grow arrays in an assignment statement. Whereas in MATLAB `a(4) = 3.2` can create the array `a = [0 0 0 3.2]` and `a(5) = 7` can grow it into `a = [0 0 0 3.2 7]`, the corresponding Julia statement `a[5] = 7` throws an error if the length of `a` is less than 5 or if this statement is the first use of the identifier `a`. Julia has [`push!`](../../base/collections/#Base.push!) and [`append!`](../../base/collections/#Base.append!), which grow `Vector`s much more efficiently than MATLAB's `a(end+1) = val`.
-   The imaginary unit `sqrt(-1)` is represented in Julia as [`im`](../../base/numbers/#Base.im), not `i` or `j` as in MATLAB.


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
-   In Julia, literal numbers without a decimal point (such as `42`) create integers instead of floating point numbers. As a result, some operations can throw a domain error if they expect a float; for example, `julia> a = -1; 2^a` throws a domain error, as the result is not an integer (see [the FAQ entry on domain errors](../faq/#faq-domain-errors) for details).
-   In Julia, multiple values are returned and assigned as tuples, e.g. `(a, b) = (1, 2)` or `a, b = 1, 2`. MATLAB's `nargout`, which is often used in MATLAB to do optional work based on the number of returned values, does not exist in Julia. Instead, users can use optional and keyword arguments to achieve similar capabilities.
-   Julia has true one-dimensional arrays. Column vectors are of size `N`, not `Nx1`. For example, [`rand(N)`](../../stdlib/Random/#Base.rand) makes a 1-dimensional array.
-   In Julia, `[x,y,z]` will always construct a 3-element array containing `x`, `y` and `z`.
    -   To concatenate in the first ("vertical") dimension use either [`vcat(x,y,z)`](../../base/arrays/#Base.vcat) or separate with semicolons (`[x; y; z]`).
    -   To concatenate in the second ("horizontal") dimension use either [`hcat(x,y,z)`](../../base/arrays/#Base.hcat) or separate with spaces (`[x y z]`).
    -   To construct block matrices (concatenating in the first two dimensions), use either [`hvcat`](../../base/arrays/#Base.hvcat) or combine spaces and semicolons (`[a b; c d]`).


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
-   In Julia, `a:b` and `a:b:c` construct `AbstractRange` objects. To construct a full vector like in MATLAB, use [`collect(a:b)`](../../base/collections/#Base.collect-Tuple%7BAny%7D). Generally, there is no need to call `collect` though. An `AbstractRange` object will act like a normal array in most cases but is more efficient because it lazily computes its values. This pattern of creating specialized objects instead of full arrays is used frequently, and is also seen in functions such as [`range`](../../base/math/#Base.range), or with iterators such as `enumerate`, and `zip`. The special objects can mostly be used as if they were normal arrays.
-   Functions in Julia return values from their last expression or the `return` keyword instead of listing the names of variables to return in the function definition (see [The return Keyword](../functions/#The-return-Keyword) for details).
-   A Julia script may contain any number of functions, and all definitions will be externally visible when the file is loaded. Function definitions can be loaded from files outside the current working directory.
-   In Julia, reductions such as [`sum`](../../base/collections/#Base.sum), [`prod`](../../base/collections/#Base.prod), and [`maximum`](../../base/collections/#Base.maximum) are performed over every element of an array when called with a single argument, as in `sum(A)`, even if `A` has more than one dimension.


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
-   In Julia, parentheses must be used to call a function with zero arguments, like in [`rand()`](../../stdlib/Random/#Base.rand).
-   Julia discourages the use of semicolons to end statements. The results of statements are not automatically printed (except at the interactive prompt), and lines of code do not need to end with semicolons. [`println`](../../base/io-network/#Base.println) or [`@printf`](../../stdlib/Printf/#Printf.@printf) can be used to print specific output.
-   In Julia, if `A` and `B` are arrays, logical comparison operations like `A == B` do not return an array of booleans. Instead, use `A .== B`, and similarly for the other boolean operators like [`<`](../../base/math/#Base.:%3C), [`>`](../../base/math/#Base.:%3E).
-   In Julia, the operators [`&`](../../base/math/#Base.:&), [`|`](../../base/math/#Base.:%7C), and [`⊻`](../../base/math/#Base.xor) ([`xor`](../../base/math/#Base.xor)) perform the bitwise operations equivalent to `and`, `or`, and `xor` respectively in MATLAB, and have precedence similar to Python's bitwise operators (unlike C). They can operate on scalars or element-wise across arrays and can be used to combine logical arrays, but note the difference in order of operations: parentheses may be required (e.g., to select elements of `A` equal to 1 or 2 use `(A .== 1) .| (A .== 2)`).
-   In Julia, the elements of a collection can be passed as arguments to a function using the splat operator `...`, as in `xs=[1,2]; f(xs...)`.


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
-   Julia's [`svd`](../../stdlib/LinearAlgebra/#LinearAlgebra.svd) returns singular values as a vector instead of as a dense diagonal matrix.
-   In Julia, `...` is not used to continue lines of code. Instead, incomplete expressions automatically continue onto the next line.
-   In both Julia and MATLAB, the variable `ans` is set to the value of the last expression issued in an interactive session. In Julia, unlike MATLAB, `ans` is not set when Julia code is run in non-interactive mode.
-   Julia's `struct`s do not support dynamically adding fields at runtime, unlike MATLAB's `class`es. Instead, use a [`Dict`](../../base/collections/#Base.Dict). Dict in Julia isn't ordered.
-   In Julia each module has its own global scope/namespace, whereas in MATLAB there is just one global scope.
-   In MATLAB, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression `x(x>3)` or in the statement `x(x>3) = []` to modify `x` in-place. In contrast, Julia provides the higher order functions [`filter`](../../base/collections/#Base.filter) and [`filter!`](../../base/collections/#Base.filter!), allowing users to write `filter(z->z>3, x)` and `filter!(z->z>3, x)` as alternatives to the corresponding transliterations `x[x.>3]` and `x = x[x.>3]`. Using [`filter!`](../../base/collections/#Base.filter!) reduces the use of temporary arrays.


## [Noteworthy differences from MATLAB](#Noteworthy-differences-from-MATLAB)
-   The analogue of extracting (or "dereferencing") all elements of a cell array, e.g. in `vertcat(A{:})` in MATLAB, is written using the splat operator in Julia, e.g. as `vcat(A...)`.
-   In Julia, the `adjoint` function performs conjugate transposition; in MATLAB, `adjoint` provides the "adjugate" or classical adjoint, which is the transpose of the matrix of cofactors.
-   In Julia, a^b^c is evaluated a^(b^c) while in MATLAB it's (a^b)^c.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
One of Julia's goals is to provide an effective language for data analysis and statistical programming. For users coming to Julia from R, these are some noteworthy differences:
-   Julia's single quotes enclose characters, not strings.
-   Julia can create substrings by indexing into strings. In R, strings must be converted into character vectors before creating substrings.
-   In Julia, like Python but unlike R, strings can be created with triple quotes `""" ... """`. This syntax is convenient for constructing strings that contain line breaks.
-   In Julia, varargs are specified using the splat operator `...`, which always follows the name of a specific variable, unlike R, for which `...` can occur in isolation.
-   In Julia, modulus is `mod(a, b)`, not `a %% b`. `%` in Julia is the remainder operator.
-   Julia constructs vectors using brackets. Julia's `[1, 2, 3]` is the equivalent of R's `c(1, 2, 3)`.
-   In Julia, not all data structures support logical indexing. Furthermore, logical indexing in Julia is supported only with vectors of length equal to the object being indexed. For example:
    -   In R, `c(1, 2, 3, 4)[c(TRUE, FALSE)]` is equivalent to `c(1, 3)`.
    -   In R, `c(1, 2, 3, 4)[c(TRUE, FALSE, TRUE, FALSE)]` is equivalent to `c(1, 3)`.
    -   In Julia, `[1, 2, 3, 4][[true, false]]` throws a [`BoundsError`](../../base/base/#Core.BoundsError).
    -   In Julia, `[1, 2, 3, 4][[true, false, true, false]]` produces `[1, 3]`.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Like many languages, Julia does not always allow operations on vectors of different lengths, unlike R where the vectors only need to share a common index range. For example, `c(1, 2, 3, 4) + c(1, 2)` is valid R but the equivalent `[1, 2, 3, 4] + [1, 2]` will throw an error in Julia.
-   Julia allows an optional trailing comma when that comma does not change the meaning of code. This can cause confusion among R users when indexing into arrays. For example, `x[1,]` in R would return the first row of a matrix; in Julia, however, the comma is ignored, so `x[1,] == x[1]`, and will return the first element. To extract a row, be sure to use `:`, as in `x[1,:]`.
-   Julia's [`map`](../../base/collections/#Base.map) takes the function first, then its arguments, unlike `lapply(<structure>, function, ...)` in R. Similarly Julia's equivalent of `apply(X, MARGIN, FUN, ...)` in R is [`mapslices`](../../base/arrays/#Base.mapslices) where the function is the first argument.
-   Multivariate apply in R, e.g. `mapply(choose, 11:13, 1:3)`, can be written as `broadcast(binomial, 11:13, 1:3)` in Julia. Equivalently Julia offers a shorter dot syntax for vectorizing functions `binomial.(11:13, 1:3)`.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Julia uses `end` to denote the end of conditional blocks, like `if`, loop blocks, like `while`/ `for`, and functions. In lieu of the one-line `if ( cond ) statement`, Julia allows statements of the form `if cond; statement; end`, `cond && statement` and `!cond || statement`. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. `cond && (x = value)`.
-   In Julia, `<-`, `<<-` and `->` are not assignment operators.
-   Julia's `->` creates an anonymous function.
-   Julia's [`*`](../../base/math/#Base.:*-Tuple%7BAny,%20Vararg%7BAny%7D%7D) operator can perform matrix multiplication, unlike in R. If `A` and `B` are matrices, then `A * B` denotes a matrix multiplication in Julia, equivalent to R's `A %*% B`. In R, this same notation would perform an element-wise (Hadamard) product. To get the element-wise multiplication operation, you need to write `A .* B` in Julia.
-   Julia performs matrix transposition using the `transpose` function and conjugated transposition using the `'` operator or the `adjoint` function. Julia's `transpose(A)` is therefore equivalent to R's `t(A)`. Additionally a non-recursive transpose in Julia is provided by the `permutedims` function.
-   Julia does not require parentheses when writing `if` statements or `for`/`while` loops: use `for i in [1, 2, 3]` instead of `for (i in c(1, 2, 3))` and `if i == 1` instead of `if (i == 1)`.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Julia does not treat the numbers `0` and `1` as Booleans. You cannot write `if (1)` in Julia, because `if` statements accept only booleans. Instead, you can write `if true`, `if Bool(1)`, or `if 1==1`.
-   Julia does not provide `nrow` and `ncol`. Instead, use `size(M, 1)` for `nrow(M)` and `size(M, 2)` for `ncol(M)`.
-   Julia is careful to distinguish scalars, vectors and matrices. In R, `1` and `c(1)` are the same. In Julia, they cannot be used interchangeably.
-   Julia's [`diag`](../../stdlib/LinearAlgebra/#LinearAlgebra.diag) and [`diagm`](../../stdlib/LinearAlgebra/#LinearAlgebra.diagm) are not like R's.
-   Julia cannot assign to the results of function calls on the left hand side of an assignment operation: you cannot write `diag(M) = fill(1, n)`.
-   Julia discourages populating the main namespace with functions. Most statistical functionality for Julia is found in [packages](https://pkg.julialang.org/) under the [JuliaStats organization](https://github.com/JuliaStats). For example:
    -   Functions pertaining to probability distributions are provided by the [Distributions package](https://github.com/JuliaStats/Distributions.jl).
    -   The [DataFrames package](https://github.com/JuliaData/DataFrames.jl) provides data frames.
    -   Generalized linear models are provided by the [GLM package](https://github.com/JuliaStats/GLM.jl).


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Julia provides tuples and real hash tables, but not R-style lists. When returning multiple items, you should typically use a tuple or a named tuple: instead of `list(a = 1, b = 2)`, use `(1, 2)` or `(a=1, b=2)`.
-   Julia encourages users to write their own types, which are easier to use than S3 or S4 objects in R. Julia's multiple dispatch system means that `table(x::TypeA)` and `table(x::TypeB)` act like R's `table.TypeA(x)` and `table.TypeB(x)`.
-   In Julia, values are not copied when assigned or passed to a function. If a function modifies an array, the changes will be visible in the caller. This is very different from R and allows new functions to operate on large data structures much more efficiently.
-   In Julia, vectors and matrices are concatenated using [`hcat`](../../base/arrays/#Base.hcat), [`vcat`](../../base/arrays/#Base.vcat) and [`hvcat`](../../base/arrays/#Base.hvcat), not `c`, `rbind` and `cbind` like in R.
-   In Julia, a range like `a:b` is not shorthand for a vector like in R, but is a specialized `AbstractRange` object that is used for iteration. To convert a range into a vector, use [`collect(a:b)`](../../base/collections/#Base.collect-Tuple%7BAny%7D).
-   The `:` operator has a different precedence in R and Julia. In particular, in Julia arithmetic operators have higher precedence than the `:` operator, whereas the reverse is true in R. For example, `1:n-1` in Julia is equivalent to `1:(n-1)` in R.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Julia's [`max`](../../base/math/#Base.max) and [`min`](../../base/math/#Base.min) are the equivalent of `pmax` and `pmin` respectively in R, but both arguments need to have the same dimensions. While [`maximum`](../../base/collections/#Base.maximum) and [`minimum`](../../base/collections/#Base.minimum) replace `max` and `min` in R, there are important differences.
-   Julia's [`sum`](../../base/collections/#Base.sum), [`prod`](../../base/collections/#Base.prod), [`maximum`](../../base/collections/#Base.maximum), and [`minimum`](../../base/collections/#Base.minimum) are different from their counterparts in R. They all accept an optional keyword argument `dims`, which indicates the dimensions, over which the operation is carried out. For instance, let `A = [1 2; 3 4]` in Julia and `B <- rbind(c(1,2),c(3,4))` be the same matrix in R. Then `sum(A)` gives the same result as `sum(B)`, but `sum(A, dims=1)` is a row vector containing the sum over each column and `sum(A, dims=2)` is a column vector containing the sum over each row. This contrasts to the behavior of R, where separate `colSums(B)` and `rowSums(B)` functions provide these functionalities. If the `dims` keyword argument is a vector, then it specifies all the dimensions over which the sum is performed, while retaining the dimensions of the summed array, e.g. `sum(A, dims=(1,2)) == hcat(10)`. It should be noted that there is no error checking regarding the second argument.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   Julia has several functions that can mutate their arguments. For example, it has both [`sort`](../../base/sort/#Base.sort) and [`sort!`](../../base/sort/#Base.sort!).
-   In R, performance requires vectorization. In Julia, almost the opposite is true: the best performing code is often achieved by using devectorized loops.
-   Julia is eagerly evaluated and does not support R-style lazy evaluation. For most users, this means that there are very few unquoted expressions or column names.
-   Julia does not support the `NULL` type. The closest equivalent is [`nothing`](../../base/constants/#Core.nothing), but it behaves like a scalar value rather than like a list. Use `x === nothing` instead of `is.null(x)`.
-   In Julia, missing values are represented by the [`missing`](../missing/#missing) object rather than by `NA`. Use [`ismissing(x)`](../../base/base/#Base.ismissing) (or `ismissing.(x)` for element-wise operation on vectors) instead of `is.na(x)`. The [`skipmissing`](../../base/base/#Base.skipmissing) function is generally used instead of `na.rm=TRUE` (though in some particular cases functions take a `skipmissing` argument).
-   Julia lacks the equivalent of R's `assign` or `get`.
-   In Julia, `return` does not require parentheses.


## [Noteworthy differences from R](#Noteworthy-differences-from-R)
-   In R, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression `x[x>3]` or in the statement `x = x[x>3]` to modify `x` in-place. In contrast, Julia provides the higher order functions [`filter`](../../base/collections/#Base.filter) and [`filter!`](../../base/collections/#Base.filter!), allowing users to write `filter(z->z>3, x)` and `filter!(z->z>3, x)` as alternatives to the corresponding transliterations `x[x.>3]` and `x = x[x.>3]`. Using [`filter!`](../../base/collections/#Base.filter!) reduces the use of temporary arrays.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   Julia's `for`, `if`, `while`, etc. blocks are terminated by the `end` keyword. Indentation level is not significant as it is in Python. Unlike Python, Julia has no `pass` keyword.
-   Strings are denoted by double quotation marks (`"text"`) in Julia (with three double quotation marks for multi-line strings), whereas in Python they can be denoted either by single (`'text'`) or double quotation marks (`"text"`). Single quotation marks are used for characters in Julia (`'c'`).
-   String concatenation is done with `*` in Julia, not `+` like in Python. Analogously, string repetition is done with `^`, not `*`. Implicit string concatenation of string literals like in Python (e.g. `'ab' 'cd' == 'abcd'`) is not done in Julia.
-   Python Lists—flexible but slow—correspond to the Julia `Vector{Any}` type or more generally `Vector{T}` where `T` is some non-concrete element type. "Fast" arrays like NumPy arrays that store elements in-place (i.e., `dtype` is `np.float64`, `[('f1', np.uint64), ('f2', np.int32)]`, etc.) can be represented by `Array{T}` where `T` is a concrete, immutable element type. This includes built-in types like `Float64`, `Int32`, `Int64` but also more complex types like `Tuple{UInt64,Float64}` and many user-defined types as well.
-   In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
-   Julia's slice indexing includes the last element, unlike in Python. `a[2:3]` in Julia is `a[1:3]` in Python.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   Unlike Python, Julia allows [AbstractArrays with arbitrary indexes](https://julialang.org/blog/2017/04/offset-arrays/). Python's special interpretation of negative indexing, `a[-1]` and `a[-2]`, should be written `a[end]` and `a[end-1]` in Julia.
-   Julia requires `end` for indexing until the last element. `x[1:]` in Python is equivalent to `x[2:end]` in Julia.
-   In Julia, `:` before any object creates a [`Symbol`](../../base/base/#Core.Symbol) or *quotes* an expression; so, `x[:5]` is same as `x[5]`. If you want to get the first `n` elements of an array, then use range indexing.
-   Julia's range indexing has the format of `x[start:step:stop]`, whereas Python's format is `x[start:(stop+1):step]`. Hence, `x[0:10:2]` in Python is equivalent to `x[1:2:10]` in Julia. Similarly, `x[::-1]` in Python, which refers to the reversed array, is equivalent to `x[end:-1:1]` in Julia.
-   In Julia, ranges can be constructed independently as `start:step:stop`, the same syntax it uses in array-indexing. The `range` function is also supported.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   In Julia, indexing a matrix with arrays like `X[[1,2], [1,3]]` refers to a sub-matrix that contains the intersections of the first and second rows with the first and third columns. In Python, `X[[1,2], [1,3]]` refers to a vector that contains the values of cell `[1,1]` and `[2,3]` in the matrix. `X[[1,2], [1,3]]` in Julia is equivalent with `X[np.ix_([0,1],[0,2])]` in Python. `X[[0,1], [0,2]]` in Python is equivalent with `X[[CartesianIndex(1,1), CartesianIndex(2,3)]]` in Julia.
-   Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.
-   Julia arrays are column-major (Fortran-ordered) whereas NumPy arrays are row-major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (see [relevant section of Performance Tips](../performance-tips/#man-performance-column-major)).
-   Julia's updating operators (e.g. `+=`, `-=`, ...) are *not in-place* whereas NumPy's are. This means `A = [1, 1]; B = A; B += [3, 3]` doesn't change values in `A`, it rather rebinds the name `B` to the result of the right-hand side `B = B + 3`, which is a new array. For in-place operation, use `B .+= 3` (see also [dot operators](../mathematical-operations/#man-dot-operators)), explicit loops, or `InplaceOps.jl`.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function `f(x=rand()) = x` returns a new random number every time it is invoked without argument. On the other hand, the function `g(x=[1,2]) = push!(x,3)` returns `[1,2,3]` every time it is called as `g()`.
-   In Julia, keyword arguments must be passed using keywords, unlike Python in which it is usually possible to pass them positionally. Attempting to pass a keyword argument positionally alters the method signature leading to a `MethodError` or calling of the wrong method.
-   In Julia `%` is the remainder operator, whereas in Python it is the modulus.
-   In Julia, the commonly used `Int` type corresponds to the machine integer type (`Int32` or `Int64`), unlike in Python, where `int` is an arbitrary length integer. This means in Julia the `Int` type will overflow, such that `2^64 == 0`. If you need larger values use another appropriate type, such as `Int128`, [`BigInt`](../../base/numbers/#Base.GMP.BigInt) or a floating point type like `Float64`.
-   The imaginary unit `sqrt(-1)` is represented in Julia as `im`, not `j` as in Python.
-   In Julia, the exponentiation operator is `^`, not `**` as in Python.
-   Julia uses `nothing` of type `Nothing` to represent a null value, whereas Python uses `None` of type `NoneType`.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   In Julia, the standard operators over a matrix type are matrix operations, whereas, in Python, the standard operators are element-wise operations. When both `A` and `B` are matrices, `A * B` in Julia performs matrix multiplication, not element-wise multiplication as in Python. `A * B` in Julia is equivalent with `A @ B` in Python, whereas `A * B` in Python is equivalent with `A .* B` in Julia.
-   The adjoint operator `'` in Julia returns an adjoint of a vector (a lazy representation of row vector), whereas the transpose operator `.T` over a vector in Python returns the original vector (non-op).
-   In Julia, a function may contain multiple concrete implementations (called *methods*), which are selected via multiple dispatch based on the types of all arguments to the call, as compared to functions in Python, which have a single implementation and no polymorphism (as opposed to Python method calls which use a different syntax and allows dispatch on the receiver of the method).
-   There are no classes in Julia. Instead there are structures (mutable or immutable), containing data but no methods.
-   Calling a method of a class instance in Python (`x = MyClass(*args); x.f(y)`) corresponds to a function call in Julia, e.g. `x = MyType(args...); f(x, y)`. In general, multiple dispatch is more flexible and powerful than the Python class system.
-   Julia structures may have exactly one abstract supertype, whereas Python classes can inherit from one or more (abstract or concrete) superclasses.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   The logical Julia program structure (Packages and Modules) is independent of the file structure, whereas the Python code structure is defined by directories (Packages) and files (Modules).
-   In Julia, it is idiomatic to split the text of large modules into multiple files, without introducing a new module per file. The code is reassembled inside a single module in a main file via `include`. While the Python equivalent (`exec`) is not typical for this use (it will silently clobber prior definitions), Julia programs are defined as a unit at the `module` level with `using` or `import`, which will only get executed once when first needed–like `include` in Python. Within those modules, the individual files that make up that module are loaded with `include` by listing them once in the intended order.
-   The ternary operator `x > 0 ? 1 : -1` in Julia corresponds to a conditional expression in Python `1 if x > 0 else -1`.
-   In Julia the `@` symbol refers to a macro, whereas in Python it refers to a decorator.
-   Exception handling in Julia is done using `try` — `catch` — `finally`, instead of `try` — `except` — `finally`. In contrast to Python, it is not recommended to use exception handling as part of the normal workflow in Julia (compared with Python, Julia is faster at ordinary control flow but slower at exception-catching).
-   In Julia loops are fast, there is no need to write "vectorized" code for performance reasons.


## [Noteworthy differences from Python](#Noteworthy-differences-from-Python)
-   Be careful with non-constant global variables in Julia, especially in tight loops. Since you can write close-to-metal code in Julia (unlike Python), the effect of globals can be drastic (see [Performance Tips](../performance-tips/#man-performance-tips)).
-   In Julia, rounding and truncation are explicit. Python's `int(3.7)` should be `floor(Int, 3.7)` or `Int(floor(3.7))` and is distinguished from `round(Int, 3.7)`. `floor(x)` and `round(x)` on their own return an integer value of the same type as `x` rather than always returning `Int`.
-   In Julia, parsing is explicit. Python's `float("3.7")` would be `parse(Float64, "3.7")` in Julia.
-   In Python, the majority of values can be used in logical contexts (e.g. `if "a":` means the following block is executed, and `if "":` means it is not). In Julia, you need explicit conversion to `Bool` (e.g. `if "a"` throws an exception). If you want to test for a non-empty string in Julia, you would explicitly write `if !isempty("")`. Perhaps surprisingly, in Python `if "False"` and `bool("False")` both evaluate to `True` (because `"False"` is a non-empty string); in Julia, `parse(Bool, "false")` returns `false`.
-   In Julia, a new local scope is introduced by most code blocks, including loops and `try` — `catch` — `finally`. Note that comprehensions (list, generator, etc.) introduce a new local scope both in Python and Julia, whereas `if` blocks do not introduce a new local scope in both languages.


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   Julia arrays are indexed with square brackets, and can have more than one dimension `A[i,j]`. This syntax is not just syntactic sugar for a reference to a pointer or address as in C/C++. See [the manual entry about array construction](../arrays/#man-multi-dim-arrays).
-   In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.
-   Julia arrays are not copied when assigned to another variable. After `A = B`, changing elements of `B` will modify `A` as well. Updating operators like `+=` do not operate in-place, they are equivalent to `A = A + B` which rebinds the left-hand side to the result of the right-hand side expression.
-   Julia arrays are column major (Fortran ordered) whereas C/C++ arrays are row major ordered by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to C/C++ (see [relevant section of Performance Tips](../performance-tips/#man-performance-column-major)).
-   Julia values are not copied when assigned or passed to a function. If a function modifies an array, the changes will be visible in the caller.
-   In Julia, whitespace is significant, unlike C/C++, so care must be taken when adding/removing whitespace from a Julia program.


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   In Julia, literal numbers without a decimal point (such as `42`) create signed integers, of type `Int`, but literals too large to fit in the machine word size will automatically be promoted to a larger size type, such as `Int64` (if `Int` is `Int32`), `Int128`, or the arbitrarily large `BigInt` type. There are no numeric literal suffixes, such as `L`, `LL`, `U`, `UL`, `ULL` to indicate unsigned and/or signed vs. unsigned. Decimal literals are always signed, and hexadecimal literals (which start with `0x` like C/C++), are unsigned, unless when they encode more than 128 bits, in which case they are of type `BigInt`. Hexadecimal literals also, unlike C/C++/Java and unlike decimal literals in Julia, have a type based on the *length* of the literal, including leading 0s. For example, `0x0` and `0x00` have type [`UInt8`](../../base/numbers/#Core.UInt8), `0x000` and `0x0000` have type [`UInt16`](../../base/numbers/#Core.UInt16), then literals with 5 to 8 hex digits have type `UInt32`, 9 to 16 hex digits type `UInt64`, 17 to 32 hex digits type `UInt128`, and more that 32 hex digits type `BigInt`. This needs to be taken into account when defining hexadecimal masks, for example `~0xf == 0xf0` is very different from `~0x000f == 0xfff0`. 64 bit `Float64` and 32 bit [`Float32`](../../base/numbers/#Core.Float32) bit literals are expressed as `1.0` and `1.0f0` respectively. Floating point literals are rounded (and not promoted to the `BigFloat` type) if they can not be exactly represented. Floating point literals are closer in behavior to C/C++. Octal (prefixed with `0o`) and binary (prefixed with `0b`) literals are also treated as unsigned (or `BigInt` for more than 128 bits).


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   In Julia, the division operator [`/`](../../base/math/#Base.:/) returns a floating point number when both operands are of integer type. To perform integer division, use [`div`](../../base/math/#Base.div) or [`÷`](../../base/math/#Base.div).
-   Indexing an `Array` with floating point types is generally an error in Julia. The Julia equivalent of the C expression `a[i / 2]` is `a[i ÷ 2 + 1]`, where `i` is of integer type.
-   String literals can be delimited with either `"` or `"""`, `"""` delimited literals can contain `"` characters without quoting it like `"\""`. String literals can have values of other variables or expressions interpolated into them, indicated by `$variablename` or `$(expression)`, which evaluates the variable name or the expression in the context of the function.
-   `//` indicates a [`Rational`](../../base/numbers/#Base.Rational) number, and not a single-line comment (which is `#` in Julia)
-   `#=` indicates the start of a multiline comment, and `=#` ends it.
-   Functions in Julia return values from their last expression(s) or the `return` keyword. Multiple values can be returned from functions and assigned as tuples, e.g. `(a, b) = myfunction()` or `a, b = myfunction()`, instead of having to pass pointers to values as one would have to do in C/C++ (i.e. `a = myfunction(&b)`.


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   Julia does not require the use of semicolons to end statements. The results of expressions are not automatically printed (except at the interactive prompt, i.e. the REPL), and lines of code do not need to end with semicolons. [`println`](../../base/io-network/#Base.println) or [`@printf`](../../stdlib/Printf/#Printf.@printf) can be used to print specific output. In the REPL, `;` can be used to suppress output. `;` also has a different meaning within `[ ]`, something to watch out for. `;` can be used to separate expressions on a single line, but are not strictly necessary in many cases, and are more an aid to readability.
-   In Julia, the operator [`⊻`](../../base/math/#Base.xor) ([`xor`](../../base/math/#Base.xor)) performs the bitwise XOR operation, i.e. [`^`](../../base/math/#Base.:%5E-Tuple%7BNumber,%20Number%7D) in C/C++. Also, the bitwise operators do not have the same precedence as C/C++, so parenthesis may be required.
-   Julia's [`^`](../../base/math/#Base.:%5E-Tuple%7BNumber,%20Number%7D) is exponentiation (pow), not bitwise XOR as in C/C++ (use [`⊻`](../../base/math/#Base.xor), or [`xor`](../../base/math/#Base.xor), in Julia)
-   Julia has two right-shift operators, `>>` and `>>>`. `>>` performs an arithmetic shift, `>>>` always performs a logical shift, unlike C/C++, where the meaning of `>>` depends on the type of the value being shifted.
-   Julia's `->` creates an anonymous function, it does not access a member via a pointer.


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   Julia does not require parentheses when writing `if` statements or `for`/`while` loops: use `for i in [1, 2, 3]` instead of `for (int i=1; i <= 3; i++)` and `if i == 1` instead of `if (i == 1)`.
-   Julia does not treat the numbers `0` and `1` as Booleans. You cannot write `if (1)` in Julia, because `if` statements accept only booleans. Instead, you can write `if true`, `if Bool(1)`, or `if 1==1`.
-   Julia uses `end` to denote the end of conditional blocks, like `if`, loop blocks, like `while`/ `for`, and functions. In lieu of the one-line `if ( cond ) statement`, Julia allows statements of the form `if cond; statement; end`, `cond && statement` and `!cond || statement`. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. `cond && (x = value)`, because of the operator precedence.
-   Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.


## [Noteworthy differences from C/C++](#Noteworthy-differences-from-C/C)
-   Julia macros operate on parsed expressions, rather than the text of the program, which allows them to perform sophisticated transformations of Julia code. Macro names start with the `@` character, and have both a function-like syntax, `@mymacro(arg1, arg2, arg3)`, and a statement-like syntax, `@mymacro arg1 arg2 arg3`. The forms are interchangeable; the function-like form is particularly useful if the macro appears within another expression, and is often clearest. The statement-like form is often used to annotate blocks, as in the distributed `for` construct: `@distributed for i in 1:n; #= body =#; end`. Where the end of the macro construct may be unclear, use the function-like form.
-   Julia has an enumeration type, expressed using the macro `@enum(name, value1, value2, ...)` For example: `@enum(Fruit, banana=1, apple, pear)`
-   By convention, functions that modify their arguments have a `!` at the end of the name, for example `push!`.
-   In C++, by default, you have static dispatch, i.e. you need to annotate a function as virtual, in order to have dynamic dispatch. On the other hand, in Julia every method is "virtual" (although it's more general than that since methods are dispatched on every argument type, not only `this`, using the most-specific-declaration rule).


### [Julia ⇔ C/C++: Namespaces](#Julia-C/C:-Namespaces)
-   C/C++ `namespace`s correspond roughly to Julia `module`s.
-   There are no private globals or fields in Julia. Everything is publicly accessible through fully qualified paths (or relative paths, if desired).
-   `using MyNamespace::myfun` (C++) corresponds roughly to `import MyModule: myfun` (Julia).
-   `using namespace MyNamespace` (C++) corresponds roughly to `using MyModule` (Julia)
    -   In Julia, only `export`ed symbols are made available to the calling module.
    -   In C++, only elements found in the included (public) header files are made available.
-   Caveat: `import`/`using` keywords (Julia) also *load* modules (see below).
-   Caveat: `import`/`using` (Julia) works only at the global scope level (`module`s)
    -   In C++, `using namespace X` works within arbitrary scopes (ex: function scope).


### [Julia ⇔ C/C++: Module loading](#Julia-C/C:-Module-loading)
-   When you think of a C/C++ "**library**", you are likely looking for a Julia "**package**".
    -   Caveat: C/C++ libraries often house multiple "software modules" whereas Julia "packages" typically house one.
    -   Reminder: Julia `module`s are global scopes (not necessarily "software modules").
-   **Instead of build/`make` scripts**, Julia uses "Project Environments" (sometimes called either "Project" or "Environment").
    -   Build scripts are only needed for more complex applications (like those needing to compile or download C/C++ executables).
    -   To develop application or project in Julia, you can initialize its root directory as a "Project Environment", and house application-specific code/packages there. This provides good control over project dependencies, and future reproducibility.
    -   Available packages are added to a "Project Environment" with the `Pkg.add()` function or Pkg REPL mode. (This does not **load** said package, however).
    -   The list of available packages (direct dependencies) for a "Project Environment" are saved in its `Project.toml` file.
    -   The *full* dependency information for a "Project Environment" is auto-generated & saved in its `Manifest.toml` file by `Pkg.resolve()`.
-   Packages ("software modules") available to the "Project Environment" are loaded with `import` or `using`.
    -   In C/C++, you `#include <moduleheader>` to get object/function declarations, and link in libraries when you build the executable.


### [Julia ⇔ C/C++: Module loading](#Julia-C/C:-Module-loading)
    -   In Julia, calling using/import again just brings the existing module into scope, but does not load it again (similar to adding the non-standard `#pragma once` to C/C++).
-   **Directory-based package repositories** (Julia) can be made available by adding repository paths to the `Base.LOAD_PATH` array.
    -   Packages from directory-based repositories do not require the `Pkg.add()` tool prior to being loaded with `import` or `using`. They are simply available to the project.
    -   Directory-based package repositories are the **quickest solution** to developing local libraries of "software modules".


### [Julia ⇔ C/C++: Assembling modules](#Julia-C/C:-Assembling-modules)
-   In C/C++, `.c`/`.cpp` files are compiled & added to a library with build/`make` scripts.
    -   In Julia, `import [PkgName]`/`using [PkgName]` statements load `[PkgName].jl` located in a package's `[PkgName]/src/` subdirectory.
    -   In turn, `[PkgName].jl` typically loads associated source files with calls to `include "[someotherfile].jl"`.
-   `include "./path/to/somefile.jl"` (Julia) is very similar to `#include "./path/to/somefile.jl"` (C/C++).
    -   However `include "..."` (Julia) is not used to include header files (not required).
    -   **Do not use** `include "..."` (Julia) to load code from other "software modules" (use `import`/`using` instead).
    -   `include "path/to/some/module.jl"` (Julia) would instantiate multiple versions of the same code in different modules (creating *distinct* types (etc.) with the *same* names).
    -   `include "somefile.jl"` is typically used to assemble multiple files *within the same Julia package* ("software module"). It is therefore relatively straightforward to ensure file are `include`d only once (No `#ifdef` confusion).


### [Julia ⇔ C/C++: Module interface](#Julia-C/C:-Module-interface)
-   C++ exposes interfaces using "public" `.h`/`.hpp` files whereas Julia `module`s mark specific symbols that are intended for their users as `public`or `export`ed.
    -   Often, Julia `module`s simply add functionality by generating new "methods" to existing functions (ex: `Base.push!`).
    -   Developers of Julia packages therefore cannot rely on header files for interface documentation.
    -   Interfaces for Julia packages are typically described using docstrings, README.md, static web pages, ...
-   Some developers choose not to `export` all symbols required to use their package/module, but should still mark unexported user facing symbols as `public`.
    -   Users might be expected to access these components by qualifying functions/structs/... with the package/module name (ex: `MyModule.run_this_task(...)`).


### [Julia ⇔ C/C++: Quick reference](#Julia-C/C:-Quick-reference)
| Software Concept                | Julia                                                                             | C/C++                                                      |
|:--------------------------------|:----------------------------------------------------------------------------------|:-----------------------------------------------------------|
| unnamed scope                   | `begin` ... `end`                                                                 | `{` ... `}`                                                |
| function scope                  | `function x()` ... `end`                                                          | `int x() {` ... `}`                                        |
| global scope                    | `module MyMod` ... `end`                                                          | `namespace MyNS {` ... `}`                                 |
| software module                 | A Julia "package"                                                                 | `.h`/`.hpp` files\
+compiled `somelib.a`                |
| assembling\
software modules | `SomePkg.jl`: ...\
`import("subfile1.jl")`\
`import("subfile2.jl")`\
... | `$(AR) *.o` ⇒ `somelib.a`                             |
| import\
software module      | `import SomePkg`                                                                  | `#include <somelib>`\
+link in `somelib.a`              |
| module library                  | `LOAD_PATH[]`, \*Git repository,\
\*\*custom package registry                  | more `.h`/`.hpp` files\
+bigger compiled `somebiglib.a` |


### [Julia ⇔ C/C++: Quick reference](#Julia-C/C:-Quick-reference)
\* The Julia package manager supports registering multiple packages from a single Git repository.\
 \* This allows users to house a library of related packages in a single repository.\
 \*\* Julia registries are primarily designed to provide versioning \\& distribution of packages.\
 \*\* Custom package registries can be used to create a type of module library.


## [Noteworthy differences from Common Lisp](#Noteworthy-differences-from-Common-Lisp)
-   Julia uses 1-based indexing for arrays by default, and it can also handle arbitrary [index offsets](../../devdocs/offset-arrays/#man-custom-indices).
-   Functions and variables share the same namespace (“Lisp-1”).
-   There is a [`Pair`](../../base/collections/#Core.Pair) type, but it is not meant to be used as a `COMMON-LISP:CONS`. Various iterable collections can be used interchangeably in most parts of the language (eg splatting, tuples, etc). `Tuple`s are the closest to Common Lisp lists for *short* collections of heterogeneous elements. Use `NamedTuple`s in place of alists. For larger collections of homogeneous types, `Array`s and `Dict`s should be used.
-   The typical Julia workflow for prototyping also uses continuous manipulation of the image, implemented with the [Revise.jl](https://github.com/timholy/Revise.jl) package.
-   For performance, Julia prefers that operations have [type stability](../faq/#man-type-stability). Where Common Lisp abstracts away from the underlying machine operations, Julia cleaves closer to them. For example:
    -   Integer division using `/` always returns a floating-point result, even if the computation is exact.
        -   `//` always returns a rational result
        -   `÷` always returns a (truncated) integer result
    -   Bignums are supported, but conversion is not automatic; ordinary integers [overflow](../faq/#faq-integer-arithmetic).


## [Noteworthy differences from Common Lisp](#Noteworthy-differences-from-Common-Lisp)
    -   Complex numbers are supported, but to get complex results, [you need complex inputs](../faq/#faq-domain-errors).
    -   There are multiple Complex and Rational types, with different component types.
-   Modules (namespaces) can be hierarchical. [`import`](../../base/base/#import) and [`using`](../../base/base/#using) have a dual role: they load the code and make it available in the namespace. `import` for only the module name is possible (roughly equivalent to `ASDF:LOAD-OP`). Slot names don't need to be exported separately. Global variables can't be assigned to from outside the module (except with `eval(mod, :(var = val))` as an escape hatch).
-   Macros start with `@`, and are not as seamlessly integrated into the language as Common Lisp; consequently, macro usage is not as widespread as in the latter. A form of hygiene for [macros](../metaprogramming/#Metaprogramming) is supported by the language. Because of the different surface syntax, there is no equivalent to `COMMON-LISP:&BODY`.
-   *All* functions are generic and use multiple dispatch. Argument lists don't have to follow the same template, which leads to a powerful idiom (see [`do`](../../base/base/#do)). Optional and keyword arguments are handled differently. Method ambiguities are not resolved like in the Common Lisp Object System, necessitating the definition of a more specific method for the intersection.


## [Noteworthy differences from Common Lisp](#Noteworthy-differences-from-Common-Lisp)
-   Symbols do not belong to any package, and do not contain any values *per se*. `M.var` evaluates the symbol `var` in the module `M`.
-   A functional programming style is fully supported by the language, including closures, but isn't always the idiomatic solution for Julia. Some [workarounds](../performance-tips/#man-performance-captured) may be necessary for performance when modifying captured variables.
------------------------------------------------------------------------


# Command-line Interface · The Julia Language
Source: https://docs.julialang.org/en/v1/manual/command-line-interface/


# [Command-line Interface](#cli)


## [Using arguments inside scripts](#Using-arguments-inside-scripts)
When running a script using `julia`, you can pass additional arguments to your script:
```julia
$ julia script.jl arg1 arg2...
```
These additional command-line arguments are passed in the global constant `ARGS`. The name of the script itself is passed in as the global `PROGRAM_FILE`. Note that `ARGS` is also set when a Julia expression is given using the `-e` option on the command line (see the `julia` help output below) but `PROGRAM_FILE` will be empty. For example, to just print the arguments given to a script, you could do this:
```julia
$ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar

foo
bar
```
Or you could put that code into a script and run it:
```julia
$ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
$ julia script.jl foo bar
script.jl
foo
bar
```
The `--` delimiter can be used to separate command-line arguments intended for the script file from arguments intended for Julia:
```julia
$ julia --color=yes -O -- script.jl arg1 arg2..
```
See also [Scripting](../faq/#man-scripting) for more information on writing Julia scripts.


## [The Main.main entry point](#The-Main.main-entry-point)
As of Julia, 1.11, `Base` exports the macro `@main`. This macro expands to the symbol `main`, but at the conclusion of executing a script or expression, `julia` will attempt to execute the function `Main.main(ARGS)` if such a function has been defined and this behavior was opted into by using the `@main` macro.
This feature is intended to aid in the unification of compiled and interactive workflows. In compiled workflows, loading the code that defines the `main` function may be spatially and temporally separated from the invocation. However, for interactive workflows, the behavior is equivalent to explicitly calling `exit(main(ARGS))` at the end of the evaluated script or expression.
The special entry point `Main.main` was added in Julia 1.11. For compatibility with prior julia versions, add an explicit `@isdefined(var"@main") ? (@main) : exit(main(ARGS))` at the end of your scripts.
To see this feature in action, consider the following definition, which will execute the print function despite there being no explicit call to `main`:
```julia
$ julia -e '(@main)(args) = println("Hello World!")'
Hello World!
$
```
Only the `main` binding in the `Main` module has this behavior and only if the macro `@main` was used within the defining module.
For example, using `hello` instead of `main` will not result in the `hello` function executing:
```julia
$ julia -e 'hello(ARGS) = println("Hello World!")'
$
```
and neither will a plain definition of `main`:
```julia
$ julia -e 'main(ARGS) = println("Hello World!")'
$
```


## [The Main.main entry point](#The-Main.main-entry-point)
However, the opt-in need not occur at definition time:
```julia
$ julia -e 'main(ARGS) = println("Hello World!"); @main'
Hello World!
$
```
The `main` binding may be imported from a package. A *hello world* package defined as
```julia
module Hello

export main
(@main)(args) = println("Hello from the package!")

end
```
may be used as:
```julia
$ julia -e 'using Hello'
Hello from the package!
$ julia -e 'import Hello' # N.B.: Execution depends on the binding not whether the package is loaded
$
```
However, note that the current best practice recommendation is to not mix application and reusable library code in the same package. Helper applications may be distributed as separate packages or as scripts with separate `main` entry points in a package's `bin` folder.


## [Parallel mode](#Parallel-mode)
Julia can be started in parallel mode with either the `-p` or the `--machine-file` options. `-p n` will launch an additional `n` worker processes, while `--machine-file file` will launch a worker for each line in file `file`. The machines defined in `file` must be accessible via a password-less `ssh` login, with Julia installed at the same location as the current host. Each machine definition takes the form `[count*][user@]host[:port] [bind_addr[:port]]`. `user` defaults to current user, `port` to the standard ssh port. `count` is the number of workers to spawn on the node, and defaults to 1. The optional `bind-to bind_addr[:port]` specifies the IP address and port that other workers should use to connect to this worker.


## [Startup file](#Startup-file)
If you have code that you want executed whenever Julia is run, you can put it in `~/.julia/config/startup.jl`:
```julia
$ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl
$ julia
Greetings! 你好! 안녕하세요?

...
```
Note that although you should have a `~/.julia` directory once you've run Julia for the first time, you may need to create the `~/.julia/config` folder and the `~/.julia/config/startup.jl` file if you use it.
To have startup code run only in [The Julia REPL](../../stdlib/REPL/#The-Julia-REPL) (and not when `julia` is *e.g.* run on a script), use [`atreplinit`](../../stdlib/REPL/#Base.atreplinit) in `startup.jl`:
```julia
atreplinit() do repl
    # ...
end
```


## [Command-line switches for Julia](#command-line-interface)
There are various ways to run Julia code and provide options, similar to those available for the `perl` and `ruby` programs:
```julia
julia [switches] -- [programfile] [args...]
```
The following is a complete list of command-line switches available when launching julia (a '\*' marks the default value, if applicable; settings marked '($)' may trigger package precompilation):
| Switch                                         | Description                                                                                |
|:-----------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `-v`, `--version`                              | Display version information                                                                                |
| `-h`, `--help`                                 | Print command-line options (this message)                                                                                |
| `--help-hidden`                                | Print uncommon options not shown by `-h`                                                                                |
| `--project[={<dir>|@.}]`                       | Set `<dir>` as the active project/environment. The default `@.` option will search through parent directories until a `Project.toml` or `JuliaProject.toml` file is found.                                                                                |
| `-J`, `--sysimage <file>`                      | Start up with the given system image file                                                                                |
| `-H`, `--home <dir>`                           | Set location of `julia` executable                                                                                |
| `--startup-file={yes*|no}`                     | Load `JULIA_DEPOT_PATH/config/startup.jl`; if [`JULIA_DEPOT_PATH`](../environment-variables/#JULIA_DEPOT_PATH) environment variable is unset, load `~/.julia/config/startup.jl`                                                                                |
| `--handle-signals={yes*|no}`                   | Enable or disable Julia's default signal handlers                                                                                |
| `--sysimage-native-code={yes*|no}`             | Use native code from system image if available                                                                                |
| `--compiled-modules={yes*|no|existing|strict}` | Enable or disable incremental precompilation of modules. The `existing` option allows use of existing compiled modules that were previously precompiled, but disallows creation of new precompile files. The `strict` option is similar, but will error if no precompile file is found.                                                                                |
| `--pkgimages={yes*|no|existing}`               | Enable or disable usage of native code caching in the form of pkgimages. The `existing` option allows use of existing pkgimages but disallows creation of new ones                                                                                |
| `-e`, `--eval <expr>`                          | Evaluate `<expr>`                                                                                |
| `-E`, `--print <expr>`                         | Evaluate `<expr>` and display the result                                                                                |
| `-m`, `--module <Package> [args]`              | Run entry point of `Package` (`@main` function) with \`args'                                                                                |
| `-L`, `--load <file>`                          | Load `<file>` immediately on all processors                                                                                |
| `-t`, `--threads {auto|N[,auto|M]}`            | Enable N\[+M\] threads; N threads are assigned to the `default` threadpool, and if M is specified, M threads are assigned to the `interactive` threadpool; `auto` tries to infer a useful default number of threads to use but the exact behavior might change in the future. Currently sets N to the number of CPUs assigned to this Julia process based on the OS-specific affinity assignment interface if supported (Linux and Windows) or to the number of CPU threads if not supported (MacOS) or if process affinity is not configured, and sets M to 1. |
| `--gcthreads=N[,M]`                            | Use N threads for the mark phase of GC and M (0 or 1) threads for the concurrent sweeping phase of GC. N is set to half of the number of compute threads and M is set to 0 if unspecified.                                                                                |
| `-p`, `--procs {N|auto}`                       | Integer value N launches N additional local worker processes; `auto` launches as many workers as the number of local CPU threads (logical cores)                                                                                |
| `--machine-file <file>`                        | Run processes on hosts listed in `<file>`                                                                                |
| `-i`, `--interactive`                          | Interactive mode; REPL runs and `isinteractive()` is true                                                                                |
| `-q`, `--quiet`                                | Quiet startup: no banner, suppress REPL warnings                                                                                |
| `--banner={yes|no|short|auto*}`                | Enable or disable startup banner                                                                                |
| `--color={yes|no|auto*}`                       | Enable or disable color text                                                                                |
| `--history-file={yes*|no}`                     | Load or save history                                                                                |
| `--depwarn={yes|no*|error}`                    | Enable or disable syntax and method deprecation warnings (`error` turns warnings into errors)                                                                                |
| `--warn-overwrite={yes|no*}`                   | Enable or disable method overwrite warnings                                                                                |
| `--warn-scope={yes*|no}`                       | Enable or disable warning for ambiguous top-level scope                                                                                |
| `-C`, `--cpu-target <target>`                  | Limit usage of CPU features up to `<target>`; set to `help` to see the available options                                                                                |
| `-O`, `--optimize={0|1|2*|3}`                  | Set the optimization level (level is 3 if `-O` is used without a level) ($)                                                                                |
| `--min-optlevel={0*|1|2|3}`                    | Set the lower bound on per-module optimization                                                                                |
| `-g`, `--debug-info={0|1*|2}`                  | Set the level of debug info generation (level is 2 if `-g` is used without a level) ($)                                                                                |
| `--inline={yes|no}`                            | Control whether inlining is permitted, including overriding `@inline` declarations                                                                                |
| `--check-bounds={yes|no|auto*}`                | Emit bounds checks always, never, or respect `@inbounds` declarations ($)                                                                                |
| `--math-mode={ieee,fast}`                      | Disallow or enable unsafe floating point optimizations (overrides `@fastmath` declaration)                                                                                |
| `--polly={yes*|no}`                            | Enable or disable the polyhedral optimizer Polly (overrides @polly declaration)                                                                                |
| `--code-coverage[={none*|user|all}]`           | Count executions of source lines (omitting setting is equivalent to `user`)                                                                                |
| `--code-coverage=@<path>`                      | Count executions but only in files that fall under the given file path/directory. The `@` prefix is required to select this option. A `@` with no path will track the current directory.                                                                                |
| `--code-coverage=tracefile.info`               | Append coverage information to the LCOV tracefile (filename supports format tokens).                                                                                |
| `--track-allocation[={none*|user|all}]`        | Count bytes allocated by each source line (omitting setting is equivalent to "user")                                                                                |
| `--track-allocation=@<path>`                   | Count bytes but only in files that fall under the given file path/directory. The `@` prefix is required to select this option. A `@` with no path will track the current directory.                                                                                |
| `--bug-report=KIND`                            | Launch a bug report session. It can be used to start a REPL, run a script, or evaluate expressions. It first tries to use BugReporting.jl installed in current environment and falls back to the latest compatible BugReporting.jl if not. For more information, see `--bug-report=help`.                                                                                |
| `--heap-size-hint=<size>`                      | Forces garbage collection if memory usage is higher than the given value. The value may be specified as a number of bytes, optionally in units of KB, MB, GB, or TB, or as a percentage of physical memory with %.                                                                                |
| `--compile={yes*|no|all|min}`                  | Enable or disable JIT compiler, or request exhaustive or minimal compilation                                                                                |
| `--output-o <name>`                            | Generate an object file (including system image data)                                                                                |
| `--output-ji <name>`                           | Generate a system image data file (.ji)                                                                                |
| `--strip-metadata`                             | Remove docstrings and source location info from system image                                                                                |
| `--strip-ir`                                   | Remove IR (intermediate representation) of compiled functions                                                                                |
| `--output-unopt-bc <name>`                     | Generate unoptimized LLVM bitcode (.bc)                                                                                |
| `--output-bc <name>`                           | Generate LLVM bitcode (.bc)                                                                                |
| `--output-asm <name>`                          | Generate an assembly file (.s)                                                                                |
| `--output-incremental={yes|no*}`               | Generate an incremental output file (rather than complete)                                                                                |
| `--trace-compile={stderr|name}`                | Print precompile statements for methods compiled during execution or save to a path                                                                                |
| `--image-codegen`                              | Force generate code in imaging mode                                                                                |
| `--permalloc-pkgimg={yes|no*}`                 | Copy the data section of package images into memory                                                                                |


## [Command-line switches for Julia](#command-line-interface)
In Julia 1.0, the default `--project=@.` option did not search up from the root directory of a Git repository for the `Project.toml` file. From Julia 1.1 forward, it does.
------------------------------------------------------------------------


# Essentials · The Julia Language
Source: https://docs.julialang.org/en/v1/base/base/


# [Essentials](#Essentials)


## [Introduction](#Introduction)
Julia Base contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of [available packages](https://julialang.org/packages/). Functions are grouped by topic below.
Some general notes:
-   To use module functions, use `import Module` to import the module, and `Module.fn(x)` to use the functions.
-   Alternatively, `using Module` will import all exported `Module` functions into the current namespace.
-   By convention, function names ending with an exclamation point (`!`) modify their arguments. Some functions have both modifying (e.g., `sort!`) and non-modifying (`sort`) versions.
The behaviors of `Base` and standard libraries are stable as defined in [SemVer](https://semver.org/) only if they are documented; i.e., included in the [Julia documentation](https://docs.julialang.org/) and not marked as unstable. See [API FAQ](../../manual/faq/#man-api) for more information.


## [Getting Around](#Getting-Around)
```julia
exit(code=0)
```
Stop the program with an exit code. The default exit code is zero, indicating that the program completed successfully. In an interactive session, `exit()` can be called with the keyboard shortcut `^D`.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/initdefs.jl#L21-L27)
```julia
atexit(f)
```
Register a zero- or one-argument function `f()` to be called at process exit. `atexit()` hooks are called in last in first out (LIFO) order and run before object finalizers.
If `f` has a method defined for one integer argument, it will be called as `f(n::Int32)`, where `n` is the current exit code, otherwise it will be called as `f()`.
The one-argument form requires Julia 1.9
Exit hooks are allowed to call `exit(n)`, in which case Julia will exit with exit code `n` (instead of the original exit code). If more than one exit hook calls `exit(n)`, then Julia will exit with the exit code corresponding to the last called exit hook that calls `exit(n)`. (Because exit hooks are called in LIFO order, "last called" is equivalent to "first registered".)
Note: Once all exit hooks have been called, no more exit hooks can be registered, and any call to `atexit(f)` after all hooks have completed will throw an exception. This situation may occur if you are registering exit hooks from background Tasks that may still be executing concurrently during shutdown.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/initdefs.jl#L394-L418)


## [Getting Around](#Getting-Around)
```julia
isinteractive() -> Bool
```
Determine whether Julia is running an interactive session.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/initdefs.jl#L35-L39)
```julia
Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int
```
Compute the amount of memory, in bytes, used by all unique objects reachable from the argument.
**Keyword Arguments**
-   `exclude`: specifies the types of objects to exclude from the traversal.
-   `chargeall`: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.
See also [`sizeof`](#Base.sizeof-Tuple%7BType%7D).
**Examples**
```julia-repl
julia> Base.summarysize(1.0)
8

julia> Base.summarysize(Ref(rand(100)))
848

julia> sizeof(Ref(rand(100)))
8
```
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/summarysize.jl#L14-L37)
```julia
__precompile__(isprecompilable::Bool)
```
Specify whether the file calling this function is precompilable, defaulting to `true`. If a module or file is *not* safely precompilable, it should call `__precompile__(false)` in order to throw an error if Julia attempts to precompile it.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/loading.jl#L2217-L2223)
```julia
Base.include([mapexpr::Function,] m::Module, path::AbstractString)
```


## [Getting Around](#Getting-Around)
Evaluate the contents of the input source file in the global scope of module `m`. Every module (except those defined with [`baremodule`](#baremodule)) has its own definition of `include` omitting the `m` argument, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to `include` will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `path`, the `include` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/loading.jl#L2763-L2780)
```julia
include([mapexpr::Function,] path::AbstractString)
```


## [Getting Around](#Getting-Around)
Evaluate the contents of the input source file in the global scope of the containing module. Every module (except those defined with `baremodule`) has its own definition of `include`, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to `include` will search relative to that path. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files. The argument `path` is normalized using [`normpath`](../file/#Base.Filesystem.normpath) which will resolve relative path tokens such as `..` and convert `/` to the appropriate path separator.
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `path`, the `include` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Use [`Base.include`](#Base.include) to evaluate a file into another module.
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/sysimg.jl#L13-L34)
```julia
include_string([mapexpr::Function,] m::Module, code::AbstractString, filename::AbstractString="string")
```
Like [`include`](#Base.include), except reads code from the given string rather than from a file.


## [Getting Around](#Getting-Around)
The optional first argument `mapexpr` can be used to transform the included code before it is evaluated: for each parsed expression `expr` in `code`, the `include_string` function actually evaluates `mapexpr(expr)`. If it is omitted, `mapexpr` defaults to [`identity`](#Base.identity).
Julia 1.5 is required for passing the `mapexpr` argument.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/loading.jl#L2704-L2715)
```julia
include_dependency(path::AbstractString; track_content::Bool=true)
```
In a module, declare that the file, directory, or symbolic link specified by `path` (relative or absolute) is a dependency for precompilation; that is, if `track_content=true` the module will need to be recompiled if the content of `path` changes (if `path` is a directory the content equals `join(readdir(path))`). If `track_content=false` recompilation is triggered when the modification time `mtime` of `path` changes.
This is only needed if your module depends on a path that is not used via [`include`](#Base.include). It has no effect outside of compilation.
Keyword argument `track_content` requires at least Julia 1.11. An error is now thrown if `path` is not readable.
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/loading.jl#L2186-L2201)
```julia
__init__
```


## [Getting Around](#Getting-Around)
The `__init__()` function in a module executes immediately *after* the module is loaded at runtime for the first time. It is called once, after all other statements in the module have been executed. Because it is called after fully importing the module, `__init__` functions of submodules will be executed first. Two typical uses of `__init__` are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. See the [manual section about modules](../../manual/modules/#modules) for more details.
**Examples**
```julia
const foo_data_ptr = Ref{Ptr{Cvoid}}(0)
function __init__()
    ccall((:foo_init, :libfoo), Cvoid, ())
    foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ())
    nothing
end
```
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/docs/basedocs.jl#L150-L170)
```julia
which(f, types)
```
Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`.
If `types` is an abstract type, then the method that would be called by `invoke` is returned.
See also: [`parentmodule`](#Base.parentmodule), [`@which`](../../stdlib/InteractiveUtils/#InteractiveUtils.@which), and [`@edit`](../../stdlib/InteractiveUtils/#InteractiveUtils.@edit).
[source](https://github.com/JuliaLang/julia/blob/9615af0f269df4d371b8010e9507ed5bae86103b/base/reflection.jl#L2209-L2217)
```julia
methods(f, [types], [module])
```
Return the method table for `f`.