Type safety helps catch values that do not fit an intended category or operation. In Julia, enumerations restrict a category to named values, while parametric types can restrict the values stored in a composite type. These checks can catch mistakes at runtime. section 13.5.1 section 18.0
Keep a category closed
With `@enum DriveStyle hex phillips slotted torx`, `DriveStyle(2)` produces `slotted`, but `DriveStyle(4)` raises an `ArgumentError`. A drive style cannot be created from an unspecified value. section 13.5.1
A type parameter can require two fields to share a type. `struct PVec2D{T} Δx::T; Δy::T end` accepts `PVec2D(2, 3)`, but cannot infer one `T` for `PVec2D(2, 3.0)`. Supplying `PVec2D{Int}(2, 3.0)` instead specifies the field type and converts the second value. section 18.3
Listing 18.7 Point and Vec2D defined so the type parameter must be a number type
import Base: +, -
struct Point{T<:Number}
x::T
y::T
end
struct Vec2D{T<:Number}
Δx::T
Δy::T
end
"Adding vector `v` to point `p` creates a new point"
function +(p::Point{T}, v::Vec2D{T}) where T
Point(p.x + v.Δx, p.y + v.Δy)
end
"Subtracting two points gives a vector"
function -(p::Point{T}, q::Point{T}) where T
Vec2D(p.x - q.x, p.y - q.y)
end
For coordinates, `T<:Number` goes further: it rules out character-valued points and vectors. The `where T` methods also require their arguments to use the same coordinate type; a method can use separate parameters when that restriction is too tight. section 18.3
Choose constraints that reflect the values an operation should accept, rather than making every type as narrow as possible. Parametric types can also help the compiler optimize code and lay out collections in memory with less boxing. section 18.3 section 18.6







