What is the Gist of the Double-Colon “::” in Julia?

There are two different ways to use the double colon “::” in Julia. First, it can be used to check to make sure a variable is of the correct type. Secondly, it can be used to force a local variable to always (locally) be of a certain data type.

The syntax for making sure the variable is the correct type is “x::type”. If x is the same type as “type,” then x is returned. If not, a TypeError is returned. For example:

julia> (1+2)::AbstractFloat
ERROR: TypeError: in typeassert, expected AbstractFloat, got Int64

julia> (1+2)::Int
3

(Code example from “Type Declarations,” JuliaLang.org)

The syntax for forcing a local variable to (locally) always have a certain data type is “x::type = value”. Trying to make x become a value that isn’t “type” will cause an error. For example:

julia> function foo(num)
           x::Int8 = num
           x
       end
foo (generic function with 1 method)

julia> foo(100)
100

julia> typeof(ans)
Int8

julia> foo(3.5)
ERROR: InexactError: Int8(3.5)

(Code example based on code found in “Type Declarations,” JuliaLang.org, which also has an example of how to do this to force the outputs of functions to be a certain type)

.

Sources:

.

Disclaimer:

I am not a professional in this field, nor do I claim to know all of the jargon that is typically used in this field. I am not summarizing my sources; I simply read from a variety of websites until I feel like I understand enough about a topic to move on to what I actually wanted to learn. If I am inaccurate in what I say or you know a better, simpler way to explain a concept, I would be happy to hear from you :).

Published by

George Evans

BS in Physics with a Minor in Mathematics.

2 thoughts on “What is the Gist of the Double-Colon “::” in Julia?”

Leave a Reply

Your email address will not be published. Required fields are marked *