6

I am trying to execute the below program.

fn main() {
    let a: u8 = 0b00000001;
    let b: u8 = 0b10101010;
    let c: u8 = 0b00001111;
    let length = a.count_ones() + a.count_zeros();
    for n in 0..length {
        println!("{}", a[n]);
        println!("{}", b[n]);
        println!("{}", c[n]);
    }
}

But I am getting error[E0608]: cannot index into a value of type `u8`

vallentin
  • 23,478
  • 6
  • 59
  • 81
Ayush Mishra
  • 567
  • 1
  • 7
  • 19
  • 2
    Related: [How do you set, clear and toggle a single bit in Rust?](https://stackoverflow.com/q/40467995) – kmdreko Dec 16 '20 at 12:41
  • Instead of `a.count_ones() + a.count_zeros()` you could also use `mem::size_of::() * 8` or `mem::size_of_val(&a) * 8`. – vallentin Dec 16 '20 at 12:48
  • @vallentin `mem::size_of::()` will _always_ be 1. OP clearly wanted the number of significant binary digits. – Peter Hall Dec 16 '20 at 12:49
  • @PeterHall I'm unsure if I'm supposed to read between the lines of anything, but `a.count_ones() + a.count_zeros()` is the same as `mem::size_of::() * 8` – vallentin Dec 16 '20 at 12:51
  • 1
    Probably `8 * mem::size_of::() - a.leading_zeros()` is what was intended? – Peter Hall Dec 16 '20 at 12:59

1 Answers1

11

Rust doesn't provide indexes into individual bits of an integer. You need to use bitwise operators instead:

This will count from the right (least to most significant bits):

fn main() {
    let a: u8 = 0b00000001;
    let b: u8 = 0b10101010;
    let c: u8 = 0b00001111;
    let length = a.count_ones() + a.count_zeros();
    for n in 0..length {
        println!("{}", a >> n & 1);
        println!("{}", b >> n & 1);
        println!("{}", c >> n & 1);
    }
}

The reason why this isn't provided is that the Index trait is defined like this:

pub trait Index<Idx>
where
    Idx: ?Sized,
{
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}

index() returns a reference, but references are always to a byte address; you can't make a reference to a single bit.


Depending on your actual use case, you may also be interested in one of these crates:

Peter Hall
  • 53,120
  • 14
  • 139
  • 204