How to get address of a slice?

How to convert slice to either *const () or usize?

&[ T ] -> *const ()

Of course, I understand it will downgrade fat pointer to slim one dropping length.
My use case is comparing addresses of two slices.

slice as *const _ as *const ()

...but there are various gotchas around comparing addresses around adjacent slices, ZSTs, slices of zero length, providence depending on the length, etc.



Though why do you need *const ()?



To compare address of a slice with address of a structure.


That does not work for me:

no method named `as_ptr` found for reference `&T1` in the current scope

Why did it get so many thumbs up? Is that preferable method?
If so it seems it is less generic.

If it’s the slice that contains the structure, a better way of expressing that is:

ptr::eq(&slice[0], structure)

And if it’s the structure that contains the slice, first of all that’s really weird and second of all do note that it’s only meaningful if the structure is #[repr(C)] or #[repr(transparent)] and contains the slice/array as its only field.

1 Like

slice is not a slice in that code, Rust is telling you that it’s an &T1.

Aha! Okay then slice as *const _ as *const () works for both slice and non slice.

std::ptr::eq() is good thing, but it does not allow comparing addresses of references on different types

Why are they different types in the first place though? That makes me suspicious of your code.

1 Like

Why not? :smiley:

Same data has several representations.

Just for the sake of auditing, can you post the code then?

I will share a link with you after publishing my crate to let you to criticize me.

Nice blog :sunglasses: Why not medium?

I am going to a bomb shelter. Russians continue to destruct my city :frowning:

Good luck. Although I am a neighbor of Russia, may there be no war in the world

1 Like

It does work AFAICT: Rust Playground

Maybe your code testing it has slice of the wrong type? The error message mention &T1 and not &[…].

1 Like

Well, the title of the thread is "address of a slice", and that's the method on slices for doing exactly what was requested:

1 Like

Incidentally, you can use std::slice::from_ref (or from_mut).

1 Like