Idimoatic way to create a reference to a slice


#1

I want to get a mutable reference to a slice and write a number to it using byteorder crate.
So I should write

(&mut buf[offset..offset + 2]).write_u16::<LittleEndian>(some_number);

Is there a more neat way to write something like this?


#2

This seems like a pretty good way to do this to me. Depending on what you’re doing, you might want to use a chunks_mut iterator or split_at_mut.


#3

See also https://github.com/steveklabnik/ref_slice


#4

You can avoid the implicit dereference in the buf[index] notation by calling index_mut directly

buf.index_mut(offset..offset + 2).write_u16::<LittleEndian>(some_number);

though it’s not shorter.


#5

It looks better for me because there is no need to return a caret while typing to close parenthesis.