Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 20, 2026 12:07
Show Gist options
  • Select an option

  • Save rust-play/fa75b119c9a1069e7691e20d30e25ba8 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/fa75b119c9a1069e7691e20d30e25ba8 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
/// A collection of digital logic gate algorithms.
struct LogicGates;
impl LogicGates {
/// NOT gate: The output is the opposite of the input.
fn not(a: u8) -> u8 {
match a {
0 => 1,
_ => 0,
}
}
/// AND gate: Output is 1 only if both inputs are 1.
fn and(a: u8, b: u8) -> u8 {
if a == 1 && b == 1 { 1 } else { 0 }
}
/// OR gate: Output is 0 only if both inputs are 0.
fn or(a: u8, b: u8) -> u8 {
if a == 1 || b == 1 { 1 } else { 0 }
}
/// NAND gate: An AND gate followed by a NOT gate.
fn nand(a: u8, b: u8) -> u8 {
Self::not(Self::and(a, b))
}
/// NOR gate: An OR gate followed by a NOT gate.
fn nor(a: u8, b: u8) -> u8 {
Self::not(Self::or(a, b))
}
}
fn main() {
let inputs = [(0, 0), (0, 1), (1, 0), (1, 1)];
println!("--- Logic Gate Truth Tables ---");
// NOT Gate
println!("\nNOT Gate:");
println!("INPUT | OUTPUT");
for i in [0, 1] {
println!(" {} | {}", i, LogicGates::not(i));
}
// AND Gate
println!("\nAND Gate:");
println!("A | B | OUTPUT");
for (a, b) in inputs {
println!("{} | {} | {}", a, b, LogicGates::and(a, b));
}
// OR Gate
println!("\nOR Gate:");
println!("A | B | OUTPUT");
for (a, b) in inputs {
println!("{} | {} | {}", a, b, LogicGates::or(a, b));
}
// NAND Gate
println!("\nNAND Gate:");
println!("A | B | OUTPUT");
for (a, b) in inputs {
println!("{} | {} | {}", a, b, LogicGates::nand(a, b));
}
// NOR Gate
println!("\nNOR Gate:");
println!("A | B | OUTPUT");
for (a, b) in inputs {
println!("{} | {} | {}", a, b, LogicGates::nor(a, b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment