To create a vector in the style of p5.js or Processing (which typically represents a 2D or 3D point or direction with x, y, and optionally z components), we can define a struct in both Rust and Zig. Below, I will provide implementations for both languages.
Rust Implementation
In Rust, we can define a Vector struct with x and y fields (and optionally z for 3D). We'll also implement some basic methods to manipulate the vector, such as addition, subtraction, and scaling.
rust
#[derive(Debug, Clone, Copy)]
struct Vector {
x: f64,
y: f64,
z: Option<f64>, // Optional z for 3D support
}
impl Vector {
// Constructor for 2D vector
fn new_2d(x: f64, y: f64) -> Self {
Vector { x, y, z: None }
}
// Constructor for 3D vector
fn new_3d(x: f64, y: f64, z: f64) -> Self {
Vector { x, y, z: Some(z) }
}
// Add two vectors
fn add(&self, other: &Vector) -> Vector {
match (self.z, other.z) {
(Some(z1), Some(z2)) => Vector::new_3d(self.x + other.x, self.y + other.y, z1 + z2),
_ => Vector::new_2d(self.x + other.x, self.y + other.y),
}
}
// Scale the vector by a scalar
fn scale(&self, scalar: f64) -> Vector {
match self.z {
Some(z) => Vector::new_3d(self.x * scalar, self.y * scalar, z * scalar),
None => Vector::new_2d(self.x * scalar, self.y * scalar),
}
}
}
fn main() {
let v1 = Vector::new_2d(3.0, 4.0);
let v2 = Vector::new_2d(1.0, 2.0);
let v3 = v1.add(&v2);
println!("v1 + v2 = {:?}", v3);
let v4 = v1.scale(2.0);
println!("v1 scaled by 2 = {:?}", v4);
}
Explanation:
The Vector struct has x and y fields, and an optional z field for 3D support.
Two constructors (new_2d and new_3d) are provided for creating 2D and 3D vectors.
Methods like add and scale are implemented to perform vector operations.
The Option<f64> type is used for the z field to handle both 2D and 3D cases elegantly.
Zig Implementation
In Zig, we can similarly define a Vector struct with x, y, and an optional z. Zig does not have built-in support for optional fields like Rust's Option, so we'll use a nullable type (?f32) for the z field.
The Vector struct has x and y fields, and a nullable z field (?f32) for 3D support.
Two constructors (new2D and new3D) are provided for creating 2D and 3D vectors.
Methods like add and scale are implemented to perform vector operations.
The if expression is used to handle the nullable z field during addition and scaling.
Key Differences Between Rust and Zig:
Optional Fields: Rust uses Option<T> for optional fields, while Zig uses nullable types (?T).
Memory Safety: Rust enforces memory safety at compile time using its ownership model, while Zig relies on explicit handling of nullability and manual memory management.
Syntax: Rust's syntax is more verbose due to its strong type system and safety features, while Zig's syntax is simpler and more direct.
Both implementations are functional and demonstrate how to create and manipulate a vector in their respective languages.