DEV Community

Discussion on: [Challenge] Add numbers without (+-*/)

Collapse
 
shekohex profile image
shekohex
const fn add<const A: usize, const B: usize>() -> usize {
    struct _Add<const A: usize, const B: usize> {
        _a: [u8; A],
        _b: [u8; B],
    }
    core::mem::size_of::<_Add<A, B>>()
}

#[test]
fn it_works() {
    assert_eq!(add::<40, 2>(), 42);
}
Enter fullscreen mode Exit fullscreen mode

Compile time execution goes brrrrrr 😂

Here is the full code with other solutions: https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=3fd17ceb138f1e2c230987bd93d93f25

Collapse
 
pyrsmk profile image
Aurélien Delogu

Can you explain the trick with size?

Collapse
 
shekohex profile image
shekohex

The memory size of the struct _Add here would be the size of _a and _b combined, in other words for any type T and length of n, [T; n] has the size of n * size_of::<T>(), and since here T is u8 and its size is just 1 byte; hence [u8; n] is just n bytes. Using this; the size of _Add would be the size of [u8; A] (A bytes) and the size of [u8; B] (B bytes); will result in total is A+B bytes.

Thread Thread
 
pyrsmk profile image
Aurélien Delogu

Yes but this is where I'm lost. Wouldn't be the returned value 2 in every case?

Thread Thread
 
shekohex profile image
shekohex

No, in the test case, A = 40 means [0u8; 40] that also means 40 bytes, and B = 2 which is [0u8; 2] that's 2 bytes, which is total of 42 bytes.

Thread Thread
 
pyrsmk profile image
Aurélien Delogu • Edited

Ah indeed, thanks! I misunderstood the syntax.

edit : that's a really smart solution btw, thanks for sharing

Collapse
 
nombrekeff profile image
Keff

Nice, that's really interesting! I like how the compiler replaces the Iterator example with a + b lol 🤣

Collapse
 
shekohex profile image
shekohex

Crazy!
(for anyone wonder what iterators, check out the rust playground link I've posted, there is other solution that uses iterators instead of const generics)

Collapse
 
thedenisnikulin profile image
Denis

Rust gang lesssgooo