Current mission: Save Happenings/2026 from becoming a DNB

Rust

From Soyjak Wiki, the free ensoyclopedia
Jump to navigationJump to search
>Though maybe you were looking for Dust?
Rust is related to Der 'CordDon't trustgroomnick changemutekickbanDMcrushspeechbubble any kittenwaifufemboyminorfurrysatanistgoonerbelugacuck (You) see. Verify for the self harm server's 18+ channel to get free nitro and gore 'p.
(Almost all) Rust users are trans btw, if that matters.
>needs rust rewrite
>RUST IS MEMORY SA-ACK!
>Hey ChatGPT, troonspile this code into a single AI generated Rust file

Rust is a programming language used by trannies or something even though all the claims of it being a tranny language are just from coping larper C niggers that have never written code beyond Hello World. It is extremely strict and particular making it highly popular among spergs. One of the most prominent claims of Rust's users is that it is as fast as C++ while being memory safe (but this is probably just glowie propaganda, as the US government has shilled Rust o algo). This is because Rust relies on a borrow checker and an ownership memory model to ensure that no invalid memory references exist, but it also allows the use of unsafe blocks to bypass the memory checker or something. It also cuts out (like trannies cutting off xheir cock) everything you need to use it and what a normal fucking language would have by fucking default, so you have to use a 'crate' (aka a library for normal people) maintained by a 'cord troon. Normal people do not understand how to use Rust for software development because it's just a powder or something. It is represented by a crab named Ferris and it was named after a kind of fungus that looks like rust and is "over-engineered for survival". The so-called Rust community is known for being composed of obnoxious ideological zealots and disproportionally transgender (according to Snopes Rust users are 41% more likely to be trans). You can also just use Java or C# for most applications which is simpler and memory safe.

Some operating systems have begun to be written in Rust which is definitely not caused by glowies. This includes Linux and Windows, which both have parts of the kernel written in Rust, due to it being a suitable language for systems programming. Also, Microsoft created George Droyd using the Rust programming language.

If you search "twitter" on the website lib.rs (an index of Rust libraries/applications like crates.io), it redirects you to a news article seething about Elon Musk doing a Nazi salute. It might do this for some other search heckin bigoted queries too.

History[edit | edit source]

Rust was first developed by Graydon Hoare of Mozilla in 2006. It originally featured object-oriented programming (however this was later removed). It was finally released in 2015. It boasted of improved performance, concurrency, type strictness, as well as memory safety despite the lack of garbage collection.

Example[edit | edit source]

#![feature(random)]
use std::random;

/// Determines whether the tranny should ack based on a given probability.
///
/// # Parameters
/// - `ack_probability`: An integer between 0 and 100 representing the chance of acking.
///
/// # Returns
/// True if the random probability is less than the ackProbability; otherwise, False.
fn should_ack(ack_probability: i32) -> bool {
    let mut prob: f64 = random::random::<i32>() as f64 * 100.0; 
    prob < ack_probability.clamp(0, 100) as f64
}

/// Main function that decides whether to ack or scream TRANS RIGHTS ARE HUMAN RIGHTS!!!!!!!! based on probability.
fn main() {
    if should_ack(41) {
        panic!("ACK!!!!");
    } else {
        println!("TRANS RIGHTS ARE HUMAN RIGHTS!!!!!!!!");
    }
}

Here is another example using the unsafe block. unsafe does not necessarily mean the code within is unsafe, but rather that most guarantees of safety do not apply to that block. In other words, these blocks offer the same level of safety as C.

/// Represents a memory-mapped GPIO control register.
///
/// The `GpioControl` struct is laid out in memory to reflect the structure of the hardware register.
/// It contains a single field `value` that corresponds to the GPIO pin state.
#[repr(C)]
struct GpioControl {
    /// The value of the GPIO register.
    ///
    /// This field represents the state of the GPIO pin. It is a 32-bit unsigned integer where
    /// different bits may control or reflect the state of different GPIO pins.
    value: u32,
}

impl GpioControl {
    /// Creates a mutable reference to the GPIO control register.
    ///
    /// This method returns a mutable reference to the memory-mapped GPIO register. The address
    /// is defined by `GPIO_BASE_ADDR`, and accessing this register allows reading and writing
    /// to the GPIO state directly. Since this is raw memory access, the operation is marked as `unsafe`.
    ///
    /// # Returns
    /// A mutable reference to the `GpioControl` struct located at the specified memory address.
    fn new() -> &'static mut GpioControl {
        unsafe {
            &mut *(GPIO_BASE_ADDR as *mut GpioControl)
        }
    }
}

/// Main function that performs unsafe operations on a GPIO control register
fn main() {
    let gpio: &'static mut GpioControl = GpioControl::new();

    // Writing a value to the GPIO register.
    unsafe {
        gpio.value = 0x1u32;
    }

    // Reading the value from the GPIO register.
    unsafe {
        let gpio_state: u32 = gpio.value;
        println!("GPIO state: {:#X}", gpio_state);
    }
}

Tutorial[edit | edit source]

Rust Tutorial | ???x450

The following is a brief tutorial on the Rust programming language. Because much of the design of Rust is influenced by C++, this tutorial makes the assumption you are at least familiar with C++; see the C++ tutorial for additional context.

Hello World[edit | edit source]

The Hello World program in Rust is as follows:

fn main() {
    println!("Hello, world!");
}

Unlike in C and C++, the standard library is always implicitly available in Rust. Also, the main function in Rust typically returns () (the "unit type"), basically similar to void in C, C++, Java, C#, etc.

println!() is a macro. Unlike macros in C/C++, Rust macros interact directly with the syntax tree of Rust rather than through direct text substitution. A macro in Rust ends with an exclamation mark at the end of its name.

Basic types[edit | edit source]

Rust consists of the following basic types:

  • i8, i16, i32, i64, i128: signed integers of sizes 8, 16, 32, 64, 128 respectively
  • u8, u16, u32, u64, u128: unsigned integers of sizes 8, 16, 32, 64, 128 respectively
  • f32, f64, f128: floating point numbers of sizes 32, 64, and 128 respectively
  • bool: a boolean value, either true or false
  • char: a single Unicode scalar value (note that unlike C/C++ where char is ASCII, char in Rust is a full Unicode character)
  • (): the unit type, has exactly one value (itself) and represents nothing, similar to void in other languages
  • str: a string slice, the most primitive string type
  • isize: a pointer-sized signed integer type, usually 8 bytes, similar to ssize_t in C
  • usize: a pointer-sized unsigned integer type, usually 8 bytes, similar to size_t in C

Other deeply fundamental types include:

  • String: a UTF-8 encoded growable string that owns its contents. It is distinct from str (the primitive).
  • Option<T>: an option type, representing either the presence of a value (of type T) or the absence of the object. If there is nothing in Option, its value is None.
  • Result<T, E>: a result type, representing either an object (of type T) or an error (of type E)
  • [T; N]: an array of objects of type T of length N
  • (T1, T2, ..., TN): a tuple type, which can hold an indefinite number of objects of any type
  • Vec<T>: a vector type, representing a dynamic array storing objects of type T
  • HashMap<K, V>: a dictionary-like type storing keys of type K, and mapping them to objects of type V

Variables[edit | edit source]

Much like in other languages, variables in Rust have a similar declaration, but use the keyword let. In most cases, the type of the variable can be omitted because it can usually be inferred by the compiler, but to explicitly label the type, use a colon.

fn main() {
    let age = 18;
    let name: &str = "Nate"; // Explicitly declare the type as &str (string slice)
    let website = "soyjak.party";
    println!("{name} is {age}, and thus old enough to post on {website}!");
}

In Rust, variables are immutable (like C/C++ const) by default. To define a compile-time constant, use const (which is like C/C++ constexpr). To allow variables to be mutable, use let mut.

let a: i32 = -5;
let mut b: u16 = 8;
const MAX_VALUE: usize = 300;

Control flow[edit | edit source]

Rust features the usual control flow structures as seen in C:

let x = 5;

if x > 0 {
    println!("x = {x} is positive");
} else if x < 0 {
    println!("x = {x} is negative");
} else {
    println!("x is exactly zero");
}

Rust also features a if let, which unwraps an Option<T>:

let opt: Option<i32> = Some(5);
if let Some(x) = opt {
    println!("x's value is {x}");
}

Also, instead of switch, Rust introduces the match block. This acts more generally than switch, particularly useful in pattern matching.

let day = 2;

match day {
    1 => println!("Monday"),
    2 => println!("Tuesday"),
    3 => println!("Wednesday"),
    _ => println!("Some other day"),
}

Loops[edit | edit source]

Rust features the same loops as seen in C and C++, and the same break and continue statements.

For loop[edit | edit source]

For loops in Rust have a different syntax, as they are iterator-based. This is more similar to the range-based for loop in C++:

// prints for i = 0, 1, 2, 3, 4
for i in 0..5 {
    println!("{i}");
}

// prints for i = 0, 1, 2, 3, 4, 5
for i in 0..=5 {
    println!("i = {i}");
}

While loop[edit | edit source]

The while loop in Rust is basically the same as in C/C++:

let mut x = 3;

while x > 0 {
    println!("x = {x}");
    x -= 1;
}

Infinite loop[edit | edit source]

In Rust, instead of using while true, there is an explicit syntax for an infinite loop:

loop {
    println!("Cobson will always be a gem!");
}

Ownership[edit | edit source]

In Rust, every value has only a single owner. Once that owner goes out of scope, the value is dropped (i.e. destroyed, freed). When a value is passed or assigned, ownership moves:

let s1 = String::from("hello");
let s2 = s1; // ownership moves to s2

// println!("{}", s1);
// Error, as s1 is no longer valid

Passing a value into a function moves it, but it can be given back by returning it. Meanwhile, it can be "borrowed", i.e. taken a reference (no ownership is taken).

Each value has one owner and there can only be one owner at a time.

Rust enforces a set of rules that ensure memory safety without a garbage collector:

  • You may have any number of immutable references (&T), OR exactly one mutable reference (&mut T), but not both simultaneously.
  • References must always be valid; there are no dangling references in Rust.
  • Borrowing does not transfer ownership in Rust.
  • A borrow ends when a variable is last used. For example:
let mut name = String::from("Cobson");

let r1 = &s;
println!("{r1}"); // last use of r1

let r2 = &mut s; // allowed now
r2.push_str(" will always be a gem!");

Reading input[edit | edit source]

To read input, use std::io::stdin() and call the read_line() function.

use std::io;

fn main() {
    println!("What's your name, nusoi?");
    let mut name = String::new();
    io::stdin()
        .read_line(&mut name)
        .expect("Failed to read name!");
    println!("{name}? That's a gemmy name.");
}

Thus, to create a star pyramid in Rust:

use std::io::{self, Write};

fn main() {
    let mut input = String::new();

    print!("Enter number of rows: ");
    Write::flush(&mut io::stdout())
        .unwrap();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read");
    let rows: i32 = input.trim()
        .parse()
        .expect("Not a number!");
    println!();
    let mut i = rows;

    while i > 0 {
        for _ in 1..=(i / 2) {
            print!(" ");
        }

        for _ in i..=rows {
            print!("*");
        }
        println!();
        i -= 2;
    }
}

Functions[edit | edit source]

In Rust, a function is declared with the fn keyword. To return a value from a function immediately, use the return keyword, but if you are at the end of the function, you can omit the return and semicolon at the end (no semicolon indicates an expression, which is returned, while a present semicolon indicates a statement and thus returns nothing (()).

fn post_bait() {
    println!("Trans rights are human rights!");
}

fn current_admin_number() -> i32 {
    6
}

Structs[edit | edit source]

A struct is like what it is in C. It defines a custom aggregate data type.

struct Nusoi {
    name: String,
    years: u16,
}

let nate: Nusoi = Nusoi {
    name: String::from("Nate Higgers"),
    years: 1,
};

However, methods cannot be defined here. Instead, you must define them in a impl block:

impl Nusoi {
    fn new(name: String, years: u16) -> Self {
        Self { name, years }
    }

    fn participate_in_raids(&self) {
        println!("OYYYY DOCTOS 'ox and 'ape this tranny!!!");
    }
}

Traits[edit | edit source]

Rust does not support inheritance like in C++ or Java, however a trait behaves similar to an interface in Java: a set of methods that a struct implements.

trait Admin {
    fn ban(&self, user: &Nusoi, reason: &str);
}

impl Admin for Nusoi {
    fn ban(&self, user: &Nusoi, reason: &str) {
        println!("Banning user {user.name} for reason: {reason}");
    }
}

Enums[edit | edit source]

Enums in Rust are similar to that of C:

enum Direction {
    North,
    South,
    East,
    West,
}

But, Rust enums are in fact much more powerful than in C. They can hold different data, and can be pattern-matched over with match:

enum Message {
    Text(String),
    Number(i32),
    Quit,
}

let m1 = Message::Text(String::from("o algo"));
let m2 = Message::Number(42);
let m3 = Message::Quit;

fn handle_message(msg: Message) {
    match msg {
        Message::Text(s) => println!("Text: {}", s),
        Message::Number(n) => println!("Number: {}", n),
        Message::Quit => println!("Quit message"),
    }
}

Enums may also have struct-like variants:

enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
}

let c = Shape::Circle { radius: 2.5 };

match c {
    Shape::Circle { radius } => println!("Circle with radius {}", radius),
    Shape::Rectangle { width, height } => {
        println!("Rectangle {} x {}", width, height)
    }
}

Furthermore, enums may also have methods with an impl block.

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
            Shape::Rectangle { width, height } => width * height,
        }
    }
}

Generics[edit | edit source]

A generic in Rust is basically what templates are in C++: they allow for flexible, reusable code by instantiating a different version of the function for each type.

use std::ops::{Add, Sub, Mul, Div};

fn identity<T>(value: T) -> T {
    value
}

let x = identity(5); // T = i32
let y = identity("Cobson"); // T = &str

trait Number: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> {}

impl<T> Number for T
where T: Copy + Add<Output = T> + Sub<Output = T> + Mul<Output = T> {}

#[derive(Debug, Clone, Copy)]
struct Point<T: Number> {
    x: T,
    y: T,
} 


Overview[edit | edit source]

This topic attracts ASPIESPlease remind those obsessed with this SNCA to breathe deeply from the toilet bowl.
WARNING: WORDSWORDSWORDS This page is a wall of text!
(You) VVILL add images and make the text less dense.
(You) WILL fill this section with relevant information NOW.
We have more in common than previously thought!

Comparison[edit | edit source]

Many will unfairly give Rust the "tranny language" reputation, but this analysis boils down to the fact that Rust has a disproportionately high rate of trannies in its community. While this is true, it does not discredit the redeeming qualities of Rust. These are:

  • Memory safety without using a garbage collector. The borrow checker is actually greatly superior when it comes to memory management. While it is strict, the rules it enforces are to prevent memory errors, such as memory leaks, segmentation faults, or undefined behaviour.
  • Rust allows for lifetime specification for increased control over when references to data are valid and ensure they do not outlive the data they point to. Similar to Rust, C++ has the Resource Acquisition is Initialisation (RAII) pattern for managing lifetimes.
  • Rust code can be equally as fast as C/C++, as it does not rely on any garbage collection or runtime, rather compiling directly to binaries like C/C++ that are executed directly on the operating system.
    • Unlike in C, undefined behaviour can only be invoked in unsafe blocks. Rust does not forbid the use of unsafe blocks, the only difference is that safety guarantees no longer exist within those blocks.
  • The borrow checker also prevents data races by ensuring that data is never simultaneously accessed or modified in unsafe ways.
  • Rust has a expressive and rich type system. Though some claim that type theory is for academia troons, the expressiveness of the type system allows for code and logic to be expressed much more succinctly. Rust uses algebraic enums and pattern matching allowing for less verbose code compared to C++ equivalents.
  • Iterators and smart pointers, and other abstractions are zero-cost in Rust. Error handling is also greatly simplified in Rust, and is not autistic like Go. Instead of using Exceptions, Rust instead uses Result<T, E> and can express absence of objects using Option<T>.
  • While object-oriented programming is not necessarily bad, Rust does not allow for inheritance. Instead, structs can only be composed upon each other, and methods are defined in impl blocks for methods. Rust has the equivalent of Java interfaces, called traits.
  • A single style of code formatting exists unlike the largely fragmented C++ code styles, which makes it much easier to just read anyone else's code or have a consistent style when using dependencies.
  • The ecosystem is much more centralised with a single distribution for the compiler (rustc) except for GCC Rust, formatter (rustfmt), package manager and build system (cargo), linter (clippy), and documentation generator (rustdoc). Meanwhile C++ has three different big compiler distributions (GCC, Clang, MSVC), many build systems (most ubiquitous is CMake, others are GNU Make, Ninja, Gradle for C++, Build2, XMake, etc.), language servers (the best is probably clangd), many package managers (vcpkg, conan, etc.) and documentation generators (most ubiquitous is Doxygen).
  • The standardisation process is much less bureaucratic than C++, it is much easier to propose an idea and get it into the language compared to C++. Also the Rust standard library is generally more comprehensive than the C++ standard library which includes a lot of crap no one wants.
  • C and (pre-C++20) C++ still heavily use the preprocessor, even for things like importing code. In C you can't even use modules and import code as modules, you have to use #include which verbatim copies the entire file contents into your source file which is extremely inefficient and wasteful. Also C macros are inferior to Rust macros which can be used for things like code generation, C macros only allow for text substitution which breaks type safety. Meanwhile Rust has things like modules built in directly to the language.
  • Some complain that Rust's package management heavily encourage using dependencies which causes dependency hell. This is partially true, but that's more of a critique of poor coding in Rust.

Some complain that Rust compiles much slower than C or C++. This might be true due to the higher amount of steps in compilation for Rust. If we analyse the steps of C/C++ compilation:

  • Preprocessing (expand all macros and preprocessor tokens, handle all file inclusions)
  • Compilation (compile code to assembly)
  • Assembling (assemble assembly code into machine code to object files)
  • Linking (link translation units to be able to reference other object files, combine all object files into single binary)

Meanwhile, the Rust pipeline of compilation is far more complex. It is as follows:

  • Parser-Expand-Resolve (parse the source code as an abstract syntax tree (AST), expand all macros, resolve all names)
  • Compilation (HIR) (convert the AST to a high-level intermediate representation (HIR) for type checking)
  • Type checking (check type safety, such as ensuring operations are valid, consistency of ownership, borrowing, lifetimes, memory safety)
  • Compilation (MIR) (translate the HIR to a mid-level intermediate representation (MIR), closer to machine code but abstracted from hardware details)
  • Borrow checking (verify that no data races, dangling references, mutable/immutable aliasing violations, invalid references, exist or violate guarantees of ownership)
  • Code generation (LLVM) (generate optimised code from the MIR using Low-Level Virtual Machine (LLVM), generating LLVM intermediate representation (LLVM IR) which is low-level and platform-agnostic, utilise the LLVM backend for inlining, loop unrolling, dead code elimination, etc. and ensure platform-specific optimisation and generate code for target architecture)
  • Assembling (LLVM) (convert the optimised intermediate representation into assembly code specific to target architecture)
  • Linking (combine all object files into a single binary, Rust by default uses static linking but dynamic linking is also possible)

Though, one should also take in to consideration that C++ uses code generation to generate specialised template code and is generally more complex, also the earlier mentioned header inclusion can slow C/C++ compilation significantly.

Meanwhile, there are valid reasons to use C and C++, such as specifically compiling code for very old systems. Also Rust is much younger than C/C++ so the amount of libraries that exist are far fewer. Also, unlike C++, Rust does not support variadic parameters in functions (instead you have to use macros for variadic functions), variadic template parameters, or function and operator overloading. Also to be honest you can just use Java if you are so worried about memory leaks and invalid memory access.

Though, at the end of the day a programming language is just a tool, not an ideology thoughbeit(erm snopes verified this and said this is untrue infact the language you use says a lot about you and can be used a way to identify where a person is from (shitskins using java or python, troons using rust etc)) . Just choose the right language to do the job o algo. Don't use a hammer when you aren't dealing with nails, or something. JUST LET PEOPLE ENJOY THINGS, OKAY???

Rust is part of a series on
Computing

>pssttt... nusoi... use free software.

➜ /languages

├ /markup/ HTMLCSSXML
├ /low_level/ AssemblyCC++C#Holy CRust
├ /high_level/ JavaGoPHPPythonSQLBashJavaScriptPowerShellActionScriptScratchRubyLuaP
└ /tutorials/ CC++C#JavaRust

➜ /software

├ /imageboards/ nusoiVichanYotsubaOpenYotsuba
├ /operating_systems/ WindowsLinuxUbuntuLinux MintAndroidTempleOSBSD
├ /applications/ Web BrowserPhotoshopFlashMS PaintIRC
├ /dev/ Free-software licenseGame developmentVim
└ /misc/ BabybotMcChallengeCAPTCHASystemdRAIDRicing4getSnarkysnappydoxingtool.batJS PaintSoyjak Party Enhanced

➜ /cyb

➜ /misc

├ /file_formats/ GIFMIDISVGWEBMWEBP
└ /hardware/ ThinkPadChromebooksWiFi

➜ /ai

SOYNY