Please create a vector (p5js / processing style) in Rust 1.87.0 (2024 edition) and in…
- User
Please create a vector (p5js / processing style) in Rust 1.87.0 (2024 edition) and in Zig 0.14.1
Assistant
Okay, here are implementations of a basic 2D vector structure, similar to what you might find in p5.js or Processing, in both Rust (targeting a recent version like 1.87.0) and Zig (0.14.1).
Both implementations will include:
xandycomponents (f32)- A constructor (
new) - Addition (
add) - Subtraction (
sub) - Scalar multiplication (
scaleormult) - Scalar division (
div) - Dot product (
dot) - Magnitude (length) (
mag) - Normalization (
normalize) - Distance between two vectors (
dist)
Rust Implementation (1.87.0 style)
This version leverages Rust's operator overloading via traits (
std::ops) for a more natural syntax, similar to p5.js.// src/main.rs or src/lib.rs use std::fmt; use std::ops::{Add, Sub, Mul, Div}; // Define the Vec2 struct #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Vec2 { pub x: f32, pub y: f32, } impl Vec2 { /// Creates a new 2D vector. #[inline] pub fn new(x: f32, y: f32) -> Self { Vec2 { x, y } } /// Creates a zero vector (0, 0). #[inline] pub fn zero() -> Self { Vec2 { x: 0.0, y: 0.0 } } /// Calculates the squared magnitude (length) of the vector. /// Faster than magnitude() as it avoids the square root. #[inline] pub fn magnitude_squared(self) -> f32 { self.x * self.x + self.y * self.y } /// Calculates the magnitude (length) of the vector. #[inline] pub fn magnitude(self) -> f32 { self.magnitude_squared().sqrt() } /// Normalizes the vector (makes its magnitude 1). /// Returns a zero vector if the magnitude is zero. #[inline] pub fn normalize(self) -> Self { let mag = self.magnitude(); if mag == 0.0 { Vec2::zero() } else { self / mag // Uses the overloaded Div trait } } /// Calculates the dot product between two vectors. #[inline] pub fn dot(self, other: Vec2) -> f32 { self.x * other.x + self.y * other.y } /// Calculates the Euclidean distance between this vector and another. #[inline] pub fn distance_to(self, other: Vec2) -> f32 { (self - other).magnitude() // Uses overloaded Sub and magnitude() } /// Calculates the squared Euclidean distance between this vector and another. #[inline] pub fn distance_squared_to(self, other: Vec2) -> f32 { (self - other).magnitude_squared() // Uses overloaded Sub and magnitude_squared() } /// Returns a string representation of the vector. pub fn to_string(self) -> String { format!("Vec2({}, {})", self.x, self.y) } } // --- Operator Overloading --- // Addition: v1 + v2 impl Add for Vec2 { type Output = Self; #[inline] fn add(self, other: Self) -> Self { Vec2 { x: self.x + other.x, y: self.y + other.y, } } } // Subtraction: v1 - v2 impl Sub for Vec2 { type Output = Self; #[inline] fn sub(self, other: Self) -> Self { Vec2 { x: self.x - other.x, y: self.y - other.y, } } } // Scalar Multiplication: v * scalar impl Mul<f32> for Vec2 { type Output = Self; #[inline] fn mul(self, scalar: f32) -> Self { Vec2 { x: self.x * scalar, y: self.y * scalar, } } } // Scalar Multiplication: scalar * v // Note: Rust doesn't automatically provide commutative multiplication for custom types. // You might want to implement `impl Mul<Vec2> for f32` if needed, but it requires // a separate import or defining `Vec2` differently. Often, just `v * scalar` is sufficient. impl Mul<Vec2> for f32 { type Output = Vec2; #[inline] fn mul(self, vector: Vec2) -> Vec2 { vector * self // Reuses the Vec2 * f32 implementation } } // Scalar Division: v / scalar impl Div<f32> for Vec2 { type Output = Self; #[inline] fn div(self, scalar: f32) -> Self { // Note: Division by zero will result in `inf` or `NaN` according to IEEE 754 rules. // Add explicit checks if different behavior is desired. Vec2 { x: self.x / scalar, y: self.y / scalar, } } } // Implement Display trait for nice printing using println!("{}", vec); impl fmt::Display for Vec2 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } // Example Usage (place in src/main.rs) /* fn main() { let mut v1 = Vec2::new(10.0, 5.0); let v2 = Vec2::new(3.0, 7.0); println!("v1: {:?}", v1); // Uses Debug derive println!("v2: {}", v2); // Uses Display trait // Arithmetic Operations let sum = v1 + v2; println!("v1 + v2 = {}", sum); let diff = v1 - v2; println!("v1 - v2 = {}", diff); let scaled = v1 * 2.0; println!("v1 * 2.0 = {}", scaled); let scaled_commute = 3.0 * v1; println!("3.0 * v1 = {}", scaled_commute); let divided = v1 / 2.5; println!("v1 / 2.5 = {}", divided); // Vector Operations let mag1 = v1.magnitude(); println!("Magnitude of v1: {}", mag1); let normalized_v1 = v1.normalize(); println!("Normalized v1: {}", normalized_v1); println!("Magnitude of normalized v1: {}", normalized_v1.magnitude()); let dot_product = v1.dot(v2); println!("Dot product of v1 and v2: {}", dot_product); let distance = v1.distance_to(v2); println!("Distance between v1 and v2: {}", distance); // Default/Copy behavior let v3 = Vec2::default(); // Equivalent to Vec2::new(0.0, 0.0) println!("Default vector: {}", v3); let v4 = v1; // v1 is copied because Vec2 is Copy v1.x = 100.0; // Modify original v1 println!("Modified v1: {}", v1); println!("Copied v4: {}", v4); // v4 remains unchanged } */To run this Rust code:
- Save the code (excluding the example usage comments) as
src/lib.rsorsrc/main.rs. - If saved as
src/main.rs, uncomment themainfunction block. - Run using Cargo:
cargo run(ifsrc/main.rs) or build and run tests (cargo test) if saving assrc/lib.rs.
Zig Implementation (0.14.1 style)
Zig does not have built-in operator overloading in the same way Rust does. Operations are typically performed using methods or standalone functions.
// main.zig const std = @import("std"); // Define the Vec2 struct pub const Vec2 = struct { x: f32, y: f32, // Constructor pub fn new(x: f32, y: f32) Vec2 { return Vec2{ .x = x, .y = y }; } // Zero vector pub fn zero() Vec2 { return Vec2{ .x = 0.0, .y = 0.0 }; } // Squared magnitude pub fn magnitudeSquared(self: Vec2) f32 { return self.x * self.x + self.y * self.y; } // Magnitude pub fn magnitude(self: Vec2) f32 { return std.math.sqrt(self.magnitudeSquared()); } // Normalize vector pub fn normalize(self: Vec2) Vec2 { const mag = self.magnitude(); if (mag == 0.0) { return Vec2.zero(); } // Zig's f32 division handles 0 correctly (inf/NaN) // but explicit check is clearer for normalization context. return self.div(mag); } // Dot product pub fn dot(self: Vec2, other: Vec2) f32 { return self.x * other.x + self.y * other.y; } // Distance between two vectors pub fn distanceTo(self: Vec2, other: Vec2) f32 { return self.sub(other).magnitude(); } // Squared distance between two vectors pub fn distanceSquaredTo(self: Vec2, other: Vec2) f32 { return self.sub(other).magnitudeSquared(); } // Addition pub fn add(self: Vec2, other: Vec2) Vec2 { return Vec2{ .x = self.x + other.x, .y = self.y + other.y, }; } // Subtraction pub fn sub(self: Vec2, other: Vec2) Vec2 { return Vec2{ .x = self.x - other.x, .y = self.y - other.y, }; } // Scalar Multiplication pub fn scale(self: Vec2, scalar: f32) Vec2 { return Vec2{ .x = self.x * scalar, .y = self.y * scalar, }; } // Commutative scalar multiplication (optional, but common) pub fn scaleFrom(scalar: f32, vector: Vec2) Vec2 { return vector.scale(scalar); } // Scalar Division pub fn div(self: Vec2, scalar: f32) Vec2 { // Note: Division by zero results in inf/NaN per IEEE 754. return Vec2{ .x = self.x / scalar, .y = self.y / scalar, }; } // Formatting for printing pub fn format(self: Vec2, maxLength: usize) ![maxLength]u8 { var buffer: [maxLength]u8 = undefined; const writer = std.fmt.BuildWriter.init(&buffer); // Use standard formatting for f32 try writer.writer().print("({d}, {d})", .{ self.x, self.y }); return writer.finalize(); } }; // Main function for example usage pub fn main() !void { const stdout_writer = std.io.getStdOut().writer(); var v1 = Vec2.new(10.0, 5.0); const v2 = Vec2.new(3.0, 7.0); // Using stdout_writer.print which handles formatting try stdout_writer.print("v1: ({d}, {d})\n", .{ v1.x, v1.y }); try stdout_writer.print("v2: ({d}, {d})\n", .{ v2.x, v2.y }); // Arithmetic Operations const sum = v1.add(v2); try stdout_writer.print("v1.add(v2) = ({d}, {d})\n", .{ sum.x, sum.y }); const diff = v1.sub(v2); try stdout_writer.print("v1.sub(v2) = ({d}, {d})\n", .{ diff.x, diff.y }); const scaled = v1.scale(2.0); try stdout_writer.print("v1.scale(2.0) = ({d}, {d})\n", .{ scaled.x, scaled.y }); const scaled_commute = Vec2.scaleFrom(3.0, v1); try stdout_writer.print("Vec2.scaleFrom(3.0, v1) = ({d}, {d})\n", .{ scaled_commute.x, scaled_commute.y }); const divided = v1.div(2.5); try stdout_writer.print("v1.div(2.5) = ({d}, {d})\n", .{ divided.x, divided.y }); // Vector Operations const mag1 = v1.magnitude(); try stdout_writer.print("Magnitude of v1: {d}\n", .{mag1}); const normalized_v1 = v1.normalize(); try stdout_writer.print("Normalized v1: ({d}, {d})\n", .{ normalized_v1.x, normalized_v1.y }); try stdout_writer.print("Magnitude of normalized v1: {d}\n", .{normalized_v1.magnitude()}); const dot_product = v1.dot(v2); try stdout_writer.print("Dot product of v1 and v2: {d}\n", .{dot_product}); const distance = v1.distanceTo(v2); try stdout_writer.print("Distance between v1 and v2: {d}\n", .{distance}); // Using the format method var buf: [32]u8 = undefined; try stdout_writer.writeAll("Formatted v1: "); try stdout_writer.writeAll(v1.format(buf.len) catch "Error formatting"); try stdout_writer.writeAll("\n"); // Zero vector and default copy behavior const v3 = Vec2.zero(); try stdout_writer.print("Zero vector: ({d}, {d})\n", .{ v3.x, v3.y }); var v4 = v1; // v1 is copied by value (structs are value types) v1.x = 100.0; try stdout_writer.print("Modified v1: ({d}, {d})\n", .{ v1.x, v1.y }); try stdout_writer.print("Copied v4: ({d}, {d})\n", .{ v4.x, v4.y }); }To run this Zig code:
- Save the code as
main.zig. - Compile and run using the Zig compiler:
zig run main.zig.
These examples provide a solid foundation for 2D vectors in both languages, mirroring the basic functionality expected from graphics libraries like p5.js or Processing.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.