Skip to content

Mutable indexing doesn't seem to work #278

Description

@nazar-pc

I use BitArray<[u8; _]> as a container and then trying to index into it.

Immutable indexing to return &bool works just fine, but attempt to return &mut bool fails:

218 |         &mut self.encoded_record_chunks_used[index]
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
    |
    = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `bitvec::array::BitArray<[u8; 8192]>`

Not sure what the reason of this is, but it is unexpected for sure.

Activity

  1. edgarogh commented on May 27, 2025

    @edgarogh

    It's impossible for a BitSlice to return a &mut bool through indexing since it doesn't contain any bool value. It only works with immutable indexing because it returns references to global &false and &true constant values.

  2. nazar-pc commented on May 27, 2025

    @nazar-pc
    Author

    True, but it could return something that is impl DerefMut<Output = bool>, achieving mostly the same result

  3. edgarogh commented on May 27, 2025

    @edgarogh

    That might be a bit odd to use, but indeed, that could work.

  4. teor2345 commented on Aug 21, 2025

    @teor2345
    Contributor

    True, but it could return something that is impl DerefMut<Output = bool>, achieving mostly the same result

    I think it would also have to impl Drop. DerefMut would return a temporary &mut bool, but we want to write the mutated value back to the original bit location. And there's no way to write directly to a bit using a &mut bool.

    So bitvec could run the bit writing code using Drop, or a "persist" method you have to call on the returned type.

  5. Timmmm commented on Mar 10, 2026

    @Timmmm

    I think this should be documented at least. I.e. how do you set single bits if you can't do this? Setting a single bit is surely a very common use case? (I think it's set).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions