Functions in Crystal

Functions are central in Crystal. We’ll learn about functions with a few different examples.

# Here's a function that takes two Int32s and returns
# their sum as an Int32.
def plus(a : Int32, b : Int32) : Int32
  # Crystal doesn't require explicit returns, it will
  # automatically return the value of the last expression.
  a + b
end

# When you have multiple consecutive parameters of
# the same type, you can omit the type for all but
# the last parameter.
def plus_plus(a, b, c : Int32) : Int32
  a + b + c
end

# Call a function just as you'd expect, with
# name(args).
res = plus(1, 2)
puts "1+2 = #{res}"

res = plus_plus(1, 2, 3)
puts "1+2+3 = #{res}"

To run the program, save it as functions.cr and use the crystal command:

$ crystal functions.cr
1+2 = 3
1+2+3 = 6

There are several other features to Crystal functions. One is multiple return values, which we’ll look at next.

Note: Crystal’s syntax is very similar to Ruby, but it adds static type checking. Unlike Go, Crystal doesn’t require explicit type annotations in many cases due to its powerful type inference system. However, we’ve included type annotations in this example for clarity.