Simple Rust Program to Add Two Vectors
Source: Dev.to
Linear algebra is the backbone of modern computing. GPUs utilize vector addition to calculate pixel positions and lighting for real‑time 3D rendering. Similarly, LLMs represent words as high‑dimensional vectors (embeddings), using mathematical operations to determine semantic relationships.
Note: Linear algebra gets abstract very quickly. This video by 3Blue1Brown is one of the best introductions to the subject:
https://www.youtube.com/watch?v=fNk_zzaMoSs&t=309s
Rust program to add two vectors
use std::io::{self, Write};
fn main() {
let vec1 = get_vec("Enter first vector (x,y): ");
let vec2 = get_vec("Enter second vector (x,y): ");
println!("Result: ({}, {})", vec1.0 + vec2.0, vec1.1 + vec2.1);
}
fn get_vec(msg: &str) -> (f32, f32) {
print!("{}", msg);
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let coords: Vec = input
.split(',')
.map(|s| s.trim().parse().unwrap_or(0.0))
.collect();
(coords[0], coords[1])
}
Save the file as add_vectors.rs.
Compile the program
rustc add_vectors.rs
Run the program
./add_vectors
Sample interaction
Enter first vector (x,y): 1,2
Enter second vector (x,y): 3,-1
Result: (4, 1)
Duplicating this on graph paper can help you visualize the process and aid in your understanding.
Rust breakdown: line‑by‑line
use std::io::{self, Write};
Imports I/O traits. Write is needed to flush the buffer so prompts appear immediately.
fn main() { ... }
The standard entry point where the program starts execution.
let vec1 = ... and let vec2 = ...
Variable bindings. let creates immutable bindings that capture the vectors returned by get_vec.
println!(...)
A declarative macro (note the !) that prints formatted text to the console. {} are placeholders for values.
fn get_vec(msg: &str) -> (f32, f32)
Function signature defining a helper that returns a tuple of two 32‑bit floating‑point numbers.
print!("{}", msg); io::stdout().flush().unwrap();
Prints the prompt and immediately flushes stdout so the user sees it before input is read.
io::stdin().read_line(&mut input).unwrap();
Reads a line from standard input into a mutable String. &mut gives the function permission to modify the variable. unwrap() panics if reading fails.
input.split(',').map(...).collect();
Creates an iterator that splits the input on commas, trims each piece, parses it to f32, and collects the results into a Vec.
parse().unwrap_or(0.0)
Attempts to convert the trimmed string slice to a float. If parsing fails, it falls back to 0.0 instead of panicking.
(coords[0], coords[1])
Returns the first two elements of the vector as a tuple representing the (x, y) coordinates.