liveBook · Manning

End keyword

As explained in Julia as a Second Language

The end keyword is a Julia syntax token that can denote the last valid position of an indexed collection as well as terminate compound constructs.

In Julia, `end` has two useful jobs. It closes a compound block, such as a function or loop. Inside square brackets, it refers to the last index of the collection being accessed, so you need not know its length in advance. section 3.4 section 4.5

Index from the end

At the REPL, try `A = collect('A':'F')`. Then `A[end]` is `'F'`, `A[end-1]` is `'E'`, and `A[begin+1:end-1]` selects `'B'` through `'E'`. `begin` is useful alongside `end` because Julia arrays can have a starting index other than 1. section 14.4

The meaning depends on where `end` appears. In a multiline function containing a `while` loop, one `end` closes the loop and another closes the function. In `A[3:end]`, it instead supplies the range’s last index. An ordinary slice copies elements; `@view A[3:end]` accesses them through a view. section 3.4 section 14.4

Listing 3.9 Code for creating a sine table stored in a function
function print_sin_table(increment, max_angle)
   angle = 0
   while angle <= max_angle
       rad = deg2rad(angle)
       x = sin(rad)
       println(x)
       angle = angle + increment
   end
end

The sine-table function makes the two closing `end` keywords easy to spot: the inner one finishes the `while` loop, and the outer one finishes the function. section 3.4

How Julia as a Second Language covers it

How deep it goes
Explains multiline function boundaries and works through vector indexing, slices, and views.
Examples
Demonstrates a sine-table function and character-vector selections including `A[end-1]` and `A[begin+1:end-1]`.
What it assumes
Builds on loops and single-line functions while introducing multiline function boundaries and bracket-based array access.
What you can do after
Practice/perform it: close nested functions and loops, and select elements relative to an array’s last index.
How it connects
Connects `end` to functions, while loops, `begin`, array slicing, and views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.