#How to make a struct with one field implement it's field's behavior?

34 messages · Page 1 of 1 (latest)

dark tartan
#

Yes, but by implementing Deref with Target = u64 for Bitboard you are saying that Bitboard is a smart pointer to a u64, which isn't wrong if it's just meant to be a wrapper struct. It also comes with all the nice auto deref stuff so in most places it just works.

pale lotus
#

Rust does support implementing traits on primitives:

#

?play ```rust
pub mod path {
pub mod to {
pub trait Trait {
fn f(self) -> bool;
}

    impl Trait for u32 {
        fn f(self) -> bool {
            self > 10
        }
    }
}

}

use path::to::Trait;

fn main() {
if 11.f() {
println!("Hello");
}
}

uncut wadiBOT
#
Hello```
carmine pond
#

you can do that, but this doesn't actually do anything

#

you could just use u64

#

because it is one

finite ingot
carmine pond
finite ingot
#

Bitboard is the local type

carmine pond
#

It is a type alias, not a type

#

It does not achieve the original question that OP asked

#

he achieved "ugh i guess i can't do what I want, i'll just use u64 then"

finite ingot
#

Oh my bad I forgot how type aliases worked

carmine pond
#

you can do that, just know that there is no type safety

#

yup

#

a new type is still the best way to approach it, although it is the most boiletplate-y

#

there is no escape hatch

#

this wouldnt really work well with things that call into_iter implicitly like if you try to do for x in bitboard {}

#

that would be unidiomatic 🙂

#

returning a vector when you could return an iterator

#

Just make a newtype 😉 They are very common in Rust

#

You can implement that operator for Bitboard

#

with a newtype you have type safety, which will help a lot with refactoring and avoid bugs

#

It's a bit of boilerplate up front but it is the best option in the long term

pale lotus
#

You can use macros to reduce the boilerplate and to not need to use ** and such.

#

Let me see what I can make.

pale lotus
#

It's missing things like subtraction and such, but that can be added very easily at the bottom.

#

But it implements them in nice ways that make it where you don't need to worry about whether it's Bitboard or &Bitboard and where you can do bitboard << 5 where 5 is any of the primitive numeric types or references to them.

The primitive types have all those implementations as well, so this brings Bitboard up to speed.

pale lotus
#

Forgot to #[inline] the methods so that the compiler will just treat the operations as operations on the wrapped u64s rather than method calls.