r/rustjerk • • Oct 14 '26

Why is my good looking rust code not working?

Post image

Hello, imn't new to rust. This rust code looks really good i must say. However, it is literally the opposite of working right now?
Current output:

4 is odd!

I just don't understand whats going on... Can some rustishn fix this devious error for me? thanks.
playground link

336 Upvotes

68 comments sorted by

148

u/karasawa_jp Oct 14 '26
fn alert_on_odd_number(n: i32) {
    return if n % 2 == 0
    {
        let n = n - 1;
        println!("{n} is odd!");
    }
}

fn main() {
    alert_on_odd_number(3);
    alert_on_odd_number(4);
}

36

u/RedstoneTier Oct 14 '26

your panic coded on alert_on_odd_number(i32::MIN); :((
this fix looks really promising though!

52

u/grittybants Oct 14 '26

remember: always build in release mode so there are no panics

22

u/RedstoneTier Oct 14 '26

me when my Cargo.toml looks like this:

[profile.dev]
overflow-checks = false

[profile.release]
overflow-checks = true

43

u/TinkmasterOverspark Oct 14 '26

You forgot to use unsafe

20

u/RedstoneTier Oct 14 '26

i'm still getting the same result... (playground)

fn alert_on_odd_number(n: i32) {
    return if unsafe
    
    {
    return if n % 2 == 0
    
    {
        println!("{n} is odd!");
    }
        
    }
    
    {
        
    }
}

fn main() {
    alert_on_odd_number(3);
    alert_on_odd_number(4);
}

10

u/fl_needs_to_restart Oct 14 '26

This is undefined behaviour.

7

u/dagbrown Oct 16 '26

It can't be! I've been reliably informed that Rust does not allow undefined behaviour!

7

u/borisko321 Oct 14 '26

Did you try rewriting it in perl?

6

u/RedstoneTier Oct 14 '26

no, i actually tried rewritting it in rust from perl and then this happened...

3

u/Sky_Klokwork Oct 14 '26

Not sure if this is one of those joke subs but seemingly inverting your test case `n % 2 != 0` should do it since odd numbers tend to have a remainder when modulo 2 is used on them.

In other news, found out about a feature I didn’t know. A bit of a strange way of doing it, but its kinda cool you can write it this way

3

u/RedstoneTier Oct 14 '26

wow thanks for the fix, will push to production immediately!!1!1

5

u/fl_needs_to_restart Oct 14 '26

You need {} else after a return if statement:

fn alert_on_odd_number(n: i32) {
    return if n % 2 == 0 {} else

    {
        println!("{n} is odd!");
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=2f4eb92ba5f14e74c894189ce67f332b

8

u/RedstoneTier Oct 14 '26

wow thanks for solving, you must be a true rustishn!

why did they make the syntax for return if's so weird? personally if i would be designing rust it would be 0.5x better.

112

u/Valuable_Leopard_799 Oct 14 '26

Lgtm, 4 is quite an odd number, as opposed to 3 which is completely normal.

17

u/particlemanwavegirl Oct 15 '26

Actually, four is cosmic, which is very odd indeed. Take the English language representation of any number and count the number of letters. If that new number isn't four, count the number of letters in that number. Eventually it will always terminate at four.

59

u/AdreKiseque Oct 14 '26

Must be a compiler bug.

25

u/akshay-nair Oct 14 '26

Ruby dev inventing rust syntax

14

u/SmoothTurtle872 Oct 14 '26

I didn't read the sub, and almost gave actual advice

3

u/Dependent_Tart_2413 Oct 15 '26

Is this a trolling? So stupid question and so much comments. Maybe u want something like 'if n % 2 != 0'

3

u/RedstoneTier Oct 16 '26

nope, i am asking the real questions here

1

u/Dependent_Tart_2413 Oct 16 '26

And my solution fixes it? Close the thread then

3

u/faultydesign Oct 16 '26

This is r/rustjerk

Wait, are you trolling too?

18

u/Thelatestart Oct 14 '26

I'm a cpp dev, so i googled 'rust "return if"' and found it doesnt exist... which means the statement is literally doing (return(if ...)) its like returning the if XD? And so your if doesnt apply to the return, but the braces after, so you only print when n%2==0

25

u/SirKastic23 Oct 14 '26

In Rust if is an expression, not a statement, meaning it can be used in expression placements like a return value.

It's essentially the same as the popular ternary expression

-6

u/NYU_VM Oct 14 '26

Yes, in rust, if is an expression but no, if is also an statement. These are contextual like for or while expressions and handled differently by the compiler based on context, one way is to have different dispatch for stmt and expression context, or other handlingethods

12

u/NeuroSynchroBonding Oct 14 '26

I think you're wrong. Chapter 8.1 of the Rust reference, which lists statements, says nothing about if statements. There is only a note about parsing saying control flow and block expressions with Unit type may end without a semicolon.

Chapter 8.2.15 describes "if expressions". There is nowhere on the spec that describes "if statements".

3

u/apocalyps3_me0w Oct 15 '26

8.1 lists expression statements, so an if expression can be an expression statement, but this if expression is not a statement because return expressions only have expression operands, although the return expression itself is an expression statement here

1

u/Demiu Oct 20 '26

Statement is an expression of which the value has been discarded. So like any expression that ends with a semicolon. A "bare" if gets "upgraded" to a statment if it's value is not used

8

u/BenchEmbarrassed7316 Oct 14 '26

Most programming languages ​​look like this:

return;
// or
return 1337;

In the first case, a type is returned that can exist in only one state. Therefore, it makes sense not to specify it. In Rust, this expression for a type that can have more than one value should look like this:

return if b { 1 } else { 2 }

In OP case, it returns the result of println, which can also be in a single state, and the compiler allows the else branch to be ignored.

3

u/syklemil Oct 15 '26

I think a better comparison would be

  • $other_lang:

      if (b) {
          return (1);
      }
      else {
          return (2);
      }
  • rust:

      return if b { 1 } else { 2 }

and they say Rust is liberal in its use of newlines … smh my head

3

u/BenchEmbarrassed7316 Oct 15 '26

Or just:

return b ? 1 : 2;

5

u/syklemil Oct 15 '26

And people have the gall to complain about Rust syntax! What is that line noise?????? Perl has gone too far

7

u/Antagonin Oct 14 '26

I legitimately can't tell if that's valid rust or not.

18

u/SOSdude Oct 14 '26

The func returns the value computed by the block { If n % 2 == 2 { println(); } } Which evaluates to nothing and is a valid return for a func with no return type. Basically the return does nothing here

6

u/tanoshikuidomouyo Oct 14 '26

An if without an else always returns (), so it's valid.

5

u/Ok-Argument7176 Oct 14 '26

They recently changed the definition of odds, so I think it's working as intended. Have you run on nightly to confirm?

5

u/SpeckyYT Oct 15 '26

bro discovered CoffeeScript syntax

4

u/denehoffman Oct 14 '26

/uj you should use `is_multiple_of`, it’s cleaner

/rj off-by-one errors like this happen because rust is 0-indexed, don’t worry about it

4

u/AdOnly69 Oct 14 '26

You should consider using c++ with gcc, rust compiler is kinda clangy

4

u/djfdhigkgfIaruflg Oct 15 '26

I see what you did there

3

u/morglod Oct 14 '26

/uj Please don't say that body in that condition should work on false branch

3

u/Azra__1 Oct 14 '26

What is the point of the return here?

3

u/avg_bndt Oct 14 '26

Needs more generics

3

u/DragonSnooz Oct 14 '26

It's working as written:

If (n % 2 == 0) // true when even
{

println!("{n} is odd);

}

every time you have an even number, you will be calling it odd.

3

u/SmoothTurtle872 Oct 14 '26

Unfixable, change it to an even number alerter, then you will know if you input an odd number because it won't trigger

5

u/stumpychubbins Oct 14 '26

Sorry for not using a code block, I’m on mobile. This is parsed as "return (if (n % 2 == 0) { println!(..); })". You’re returning the value of that if statement. Any if statement without an else will have an implicit "else { () }", which will usually cause a type error if you use if as an expression without an else. In this case, though, the true branch also returns (), as that is the implicit return of blocks ending with ;. This means that instead of returning if the condition is true, you’re executing the println if the condition is true

Unlike some languages, rust doesn’t have "return if" as a dedicated syntactic construct. You need to do "if condition { return; }"

13

u/Diligent-Slide-9234 Oct 14 '26

check the sub lol

3

u/stumpychubbins Oct 15 '26

Whoops lmao, somehow I managed to go this long without falling for a rustjerk post but it had to happen eventually

3

u/Ma4r Oct 15 '26

What language have a return if syntax wtf???

3

u/stumpychubbins Oct 15 '26

Ruby was the one I had in mind, I thought Python did too but I was confusing it with their conditional expression syntax

3

u/deven1969 Oct 17 '26

Perl allows statement modifiers at the end (if, unless, while…)

2

u/Most_Strike_93 29d ago

Is it rubyrust?

2

u/MistRider-0 Oct 14 '26 edited Oct 14 '26

fn alert_on_odd_number(n: i32) {
       if n%2 == 0 {return ()};
       println!("{n} is odd");
}

Fixed!

3

u/particlemanwavegirl Oct 15 '26

That filthy return keyword is no better than goto, particularly egregious in a function with no return value. I can't stand to see it so I'm posting the real solution and it's actually such a slight mistake it is quite funny but it's driving me nuts.

fn alert_on_odd_number(n: i32) {
    if n % 2 != 0 {
        println!("{n} is odd!");
    }
}

2

u/MistRider-0 Oct 15 '26

I thought we were all jerking, so I joined the jerk... 😔

2

u/riisen Oct 15 '26
fn alert_on_odd_number(n: i32) {
    if n & 0x1 == 1 {
        let n = n - 1;
        println!("{n} is odd!");
    }
}

fn main() {
    alert_on_odd_number(3);
    alert_on_odd_number(4);
}

2

u/DangyDanger Oct 15 '26
fn alert_on_even_number(n: i32) {
    return if n % 2 == 0
   
    {
        println!("{n} is even!);
    }
}

fn main() {
    alert_on_even_number(3);
    alert_on_even_number(4);
}

Don't thank me

2

u/andrewprograms Oct 15 '26

Pop another “bubble gum” (Zyn, assuming Palantir because of the defense nature of that algorithm)

2

u/catlifeonmars Oct 16 '26

I think you meant:

return unless n.odd?

Also don’t forget to wrap the whole thing in begin… rescue

2

u/monta_gia Oct 19 '26

what expectation result you want?

if you expect 3 to be printed also then will never happen

2

u/FlameyosFlow 23d ago

Well, that's because you didn't represent it in a rust enum, of course it won't be type safe rust code.

It should really be:

fn alert_on_odd_number(n: i32) {
    if oddness(n) is match Oddness::Odd { println!("{n} is odd!"); }
}

fn oddness(n: i32) -> Oddness {
    return match n {
        0 | 2 -> Oddness::Even,
        1 -> Oddness::Odd,
        n in ..0 -> oddness(n + 2),
        _ -> oddness(n - 2),
    };
}

pub enum Oddness {
    Odd,
    Even
}

Now your code is using a high performance, memory safe, type safe and elegant way to check if a number is even or odd :)

If you want to improve on this, you can even use the type state pattern so that you double ensure that a number can never be anything other than odd or even!

1

u/AcolyteArathok Oct 15 '26

4%2 is 0! Odd is when %2 returns a 1 Because %does the division and then returnst the rest.

1

u/TylerBreau Oct 17 '26

.... 8 years full stack dev, never used Rust before. Not familiar with the syntax but looking at what you've said...

if n % 2 == 0

4 % 2 == 0

3 % 2 != 0

Odd numbers fail your condition. I assume the {} block only runs if the condition passes. Or maybe you're missing an else statement but unless you want run code for the even case, I would just change the if-condition.

1

u/TheChief275 Oct 14 '26

'good looking' and 'rust code' are antitheses

5

u/regeya Oct 14 '26

Oh, that is evil. You know a lot of us have had our brains rotted out by Python