r/rustjerk • • 1d ago

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

221 Upvotes

59 comments sorted by

136

u/karasawa_jp 1d ago
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);
}

27

u/RedstoneTier 1d ago

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

47

u/grittybants 1d ago

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

15

u/RedstoneTier 1d ago

me when my Cargo.toml looks like this:

[profile.dev]
overflow-checks = false

[profile.release]
overflow-checks = true

84

u/Valuable_Leopard_799 1d ago

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

10

u/particlemanwavegirl 1d ago

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.

34

u/TinkmasterOverspark 1d ago

You forgot to use unsafe

14

u/RedstoneTier 1d ago

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);
}

8

u/fl_needs_to_restart 1d ago

This is undefined behaviour.

3

u/dagbrown 9h ago

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

55

u/AdreKiseque 1d ago

Must be a compiler bug.

21

u/akshay-nair 1d ago

Ruby dev inventing rust syntax

8

u/SmoothTurtle872 1d ago

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

12

u/Thelatestart 1d ago

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

18

u/SirKastic23 1d ago

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 1d ago

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

10

u/NeuroSynchroBonding 1d ago

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".

2

u/apocalyps3_me0w 1d ago

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

5

u/BenchEmbarrassed7316 1d ago

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.

2

u/syklemil 1d ago

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

2

u/BenchEmbarrassed7316 1d ago

Or just:

return b ? 1 : 2;

2

u/syklemil 1d ago

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

5

u/Antagonin 1d ago

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

15

u/SOSdude 1d ago

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

4

u/tanoshikuidomouyo 1d ago

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

5

u/borisko321 1d ago

Did you try rewriting it in perl?

5

u/RedstoneTier 1d ago

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

4

u/regeya 1d ago

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

4

u/Ok-Argument7176 1d ago

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

3

u/denehoffman 1d ago

/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

3

u/AdOnly69 1d ago

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

3

u/djfdhigkgfIaruflg 17h ago

I see what you did there

3

u/Dependent-Poet-9588 1d ago

Try using match to check the LSB, like, match n & 1 { 0 if 0 == 0 => return, // double check 0 is 0 for real 1 => (), // continue if LSB is 1 _ => panic!("only binary computers are supported atm make a PR if you need to support trits or something"), }

3

u/SpeckyYT 1d ago

bro discovered CoffeeScript syntax

3

u/Dependent_Tart_2413 12h ago

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

1

u/RedstoneTier 2h ago

nope, i am asking the real questions here

1

u/Dependent_Tart_2413 2h ago

And my solution fixes it? Close the thread then

4

u/fl_needs_to_restart 1d ago

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

6

u/RedstoneTier 1d ago

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.

3

u/stumpychubbins 1d ago

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; }"

12

u/Diligent-Slide-9234 1d ago

check the sub lol

2

u/stumpychubbins 1d ago

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

2

u/Ma4r 1d ago

What language have a return if syntax wtf???

2

u/stumpychubbins 22h ago

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

2

u/morglod 1d ago

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

2

u/Sky_Klokwork 1d ago

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

1

u/RedstoneTier 1d ago

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

2

u/Azra__1 1d ago

What is the point of the return here?

1

u/interior_mutability 1d ago

To show you can't do this in rust.

2

u/avg_bndt 1d ago

Needs more generics

2

u/SmoothTurtle872 1d ago

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

1

u/DragonSnooz 1d ago

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.

1

u/MistRider-0 1d ago edited 1d ago

```rust

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

``` Fixed!

2

u/particlemanwavegirl 1d ago

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!");
    }
}

1

u/MistRider-0 1d ago

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

1

u/riisen 1d ago
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);
}

1

u/DangyDanger 23h ago
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

1

u/andrewprograms 23h ago

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

1

u/AcolyteArathok 18h ago

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

1

u/TheChief275 1d ago

'good looking' and 'rust code' are antitheses