Collection of "surprising behaviours" in Rust. In the same spirit of wtfpython and wtfjs.

Overview

wtfrust

Collection of "surprising behaviours" in Rust. In the same spirit of wtfpython and wtfjs.

This document avoids common and general problems in programming like float arithmetics, string encodings, etc. and focus on the behaviours specific to Rust.

Luckily, most of the examples either require unsafe or get warnings from clippy.

Mutable Const

use std::sync::atomic::{AtomicU8, Ordering::Relaxed};

const a: AtomicU8 = AtomicU8::new(1);

fn main() {
    println!("{:?}", a);
    a.store(2, Relaxed);
    println!("{:?}", a);
}

Result: Print 1 twice.

Explanation: const in Rust is more like a macro replacement than a variable. It copies the value to wherever it is used as stack variables or immediate values.

Solution: 1). Use static for types with interior mutability, and use const for real constants. 2). cargo clippy.

References: the book.

Reading uninitialized memory

example taken from https://users.rust-lang.org/t/is-it-ub-to-read-uninitialized-integers-in-a-vector-why/39682/8

100 { println!("big"); } } ">
fn main() {
    let a: u32 = unsafe {
        std::mem::uninitialized()
    };

    if a < 150 {
        println!("small");
    }

    if a > 100 {
        println!("big");
    }
}

Result: It may print "small", or "big", or, in release mode, nothing.

Explanation: Reading uninitialized memory is always undefined behaviour, even for integers, and the compiler applys optimizations with the assumption that all undefined behaviour never happen.

Solution: Don't do it. Unless you are making a hacker tool, reading uninitialized memory is simply wrong. Note that dropping uninitialized memory is equally bad because it may read it during dropping. Therefore, one should always use ptr::write to write to uninitialized memory, as the move operator (=) implicitly drops the old value. Also use MaybeUninit instead of std::mem::uninitialized to protect from implicit dropping during panicking.

References: doc of std::hint::unreachable_unchecked states that "In particular, the compiler assumes that all UB must never happen, and therefore will eliminate all branches that reach to ...".

Cloning a reference

fn main() {
    let a = std::cell::RefCell::new(1);
    *a.clone().borrow_mut() += 1;
    println!("a = {:?}", a);
    
    let b = &a;
    *b.clone().borrow_mut() += 1;
    println!("b = {:?}", b);
    
    let c = &b;
    *c.clone().borrow_mut() += 1;
    println!("c = {:?}", c);
}

Result: a = 1, b = 1, c = 2.

Explanation: Rust automatically adds as much of & and * as necessary when using the "dot" method call. This behaviour becomes confusing when a reference type or smart pointer implements the same method. In this example, both RefCell and &RefCell implement Clone. Therefore, c.clone() resolves to <&_ as Clone>::clone, while for a and b it is ::clone .

Solution: 1). Use fully qualified function call syntax ::function() when there are potential ambiguity. 2). cargo clippy.

References: the book.

TODO: moving to _ is not an actual moving, rather it drops immediately.

You might also like...
A library and tool for automata and formal languages, inspired by JFLAP
A library and tool for automata and formal languages, inspired by JFLAP

Sugarcubes is a library and application for automata and formal languages. It is inspired by JFLAP, and is intended to eventually to be an alternative to JFLAP.

An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares

sh_product An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares (paper by John

Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks.
Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks.

Crates Registry Description Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks. (like Ver

First Git on Rust is reimplementation with rust in order to learn about rust, c and git.

First Git on Rust First Git on Rust is reimplementation with rust in order to learn about rust, c and git. Reference project This project refer to the

`Debug` in rust, but only supports valid rust syntax and outputs nicely formatted using pretty-please
`Debug` in rust, but only supports valid rust syntax and outputs nicely formatted using pretty-please

dbg-pls A Debug-like trait for rust that outputs properly formatted code Showcase Take the following code: let code = r#" [ "Hello, World!

An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

Rust ESP32 Example An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

dm-jitaux is a Rust-based JIT compiler using modified auxtools, dmasm and Inkwell LLVM wrapper for boosting Byond DM performance without any hassle!

dm-jitaux is a Rust-based JIT compiler using modified auxtools, dmasm and Inkwell LLVM wrapper for boosting Byond DM performance without any hassle (such as rewriting/refactroing your DM code).

Rust crate for parsing stivale and stivale 2 structures.

stivale-rs Rust crate for parsing stivale and stivale 2 structures. Resources Stivale v2 Specification Stivale Specification License Licensed under ei

Opensource diagnostic software for Daimler vehicles, inspired by Xentry and DAS, written in Rust

OPENSTAR An opensource diagnostic application for Daimler vehicles inspired by DAS and Xentry. Some of the work here is based on OpenVehicleDiag If yo

Owner
张实唯
"Who refuses to do arithmetic is doomed to talk nonsense."
张实唯
Small and simple stateful applications, designed to facilitate the monitoring of unwanted behaviors of the same.

Violet Violet é um pequeno e simples monitorador de aplicação, voltado para receber eventos de erro e estado. Instalação simples: Dependencias: Docker

Lucas Mendes Campos 3 Jun 4, 2022
secmem-proc is a crate designed to harden a process against low-privileged attackers running on the same system trying to obtain secret memory contents of the current process.

secmem-proc is a crate designed to harden a process against low-privileged attackers running on the same system trying to obtain secret memory contents of the current process. More specifically, the crate disables core dumps and tries to disable tracing on unix-like OSes.

null 3 Dec 19, 2022
A collection of exponentially-smoothed camera controllers for the Bevy Engine.

smooth-bevy-cameras A collection of exponentially-smoothed camera controllers for the Bevy Engine. Look Transform All controllers are based on a LookT

Duncan 122 Dec 24, 2022
A collection of compilers based around compiling a high level language to a Brainfuck dialect.

tf A collection of compilers based around compiling a high level language to a Brainfuck dialect. Built at, and for, the VolHacks V hackathon during O

adam mcdaniel 6 Nov 25, 2021
A collection of serverless apps that show how Fermyon's Serverless AI

A collection of serverless apps that show how Fermyon's Serverless AI (currently in private beta) works. Reference: https://developer.fermyon.com/spin/serverless-ai-tutorial

Fermyon 15 Oct 20, 2023
A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

null 4 Sep 3, 2022
A stupid macro that compiles and executes Rust and spits the output directly into your Rust code

inline-rust This is a stupid macro inspired by inline-python that compiles and executes Rust and spits the output directly into your Rust code. There

William 19 Nov 29, 2022
This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity.

bottom-bot This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity. Ever had this pro

Bottom Software Foundation 11 Dec 10, 2022
lightweight and customizable rust s-expression (s-expr) parser and printer

s-expr Rust library for S-expression like parsing and printing parser keeps track of spans, and representation (e.g. number base) number and decimal d

Vincent Hanquez 5 Oct 26, 2022
Simplify temporary email management and interaction, including message retrieval and attachment downloads, using Rust.

Tempmail The Tempmail simplifies temporary email management and interaction, including message retrieval and attachment downloads, using the Rust prog

Dilshad 6 Sep 21, 2023