Julia 1.0 Programming Complete Reference Guide
上QQ阅读APP看书,第一时间看更新

Type annotations

As we saw in Chapter 2, Variables, Types, and Operations, type-annotating a variable is done with the :: operator, such as in the function definition function write(io::IO, s::String) #... end, where the parameter io has to be of type IO, and s of type String. To put it differently, io has to be an instance of type IO, and s an instance of type String. The :: operator is, in fact, an assertion that affirms that the value on the left is of the type on the right. If this is not true, a typeassert error is thrown. Try this out in the REPL:

# see the code in Chapter 6\conversions.jl: 
(31+42)::Float64

We get an ERROR: TypeError: in typeassert, expected Float64, got Int64 error message.

This is, in addition to the method specialization for multiple dispatch, an important reason why type annotations are used in function signatures.

The operator :: can also be used in the sense of a type declaration, but only in local scope, such as in functions, as follows:

n::Int16 or local n::Int16 or n::Int16 = 5 

Every value assigned to n will be implicitly converted to the indicated type with the convert function.