Euclid, Rust, and Vector2D
Part of my learning a new programming language
is to read through an established code library
on GitHub. I'm currently studying
euclid
— a basic linear algebra
library written in Rust for the Servo web
browser engine. Here's a snippet from the
euclid::vector
module as I
currently understand it:
#[repr(C)]
pub struct Vector2D<T, U> {
pub x: T,
pub y: T,
#[doc(hidden)]
pub _unit: PhantomData<U>
}
-
Vector2D
is a two-dimensional vector implemented as a struct. A Rust struct is a custom data type that can hold multiple related and named values. This particular implementation contains three properties. -
Property
x
is the horizontal coordinate. Propertyy
is the vertical coordinate.x
andy
are defined by the genericT
, which allows them to contain any data type as long as they share the same data type. GenericT
is further defined by trait implementations so thatT
can only contain numeric primitives (u8
,i32
,f64
, etc). -
Property
_unit
implemented by genericU
typically contains an empty struct whose sole purpose is to differentiate vector spaces —Vector2D<f64, Canvas>
will not mix withVector2D<f64, DOM>
. Wrapping_unit
in aPhantomData
marker allows_unit
to be an empty data type. The Rust compiler would otherwise believe_unit
to be an error. -
All Rust modules, functions, and data structures default to private, meaning external modules cannot access them. The
pub
keyword inverts this. -
The inner workings of the Rust attribute
#[repr(C)]
are currently beyond me. The documentation claims this metadata allowsVector2D
to interact with code written in other languages as long as those languages implementC
scalars.