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.
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.
slice.as_ptr().cast::<()>()
Though why do you need *const ()
?
Thanks!
To compare address of a slice with address of a structure.
slice.as_ptr().cast::<()>()
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.
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.
Why not?
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 Why not medium?
I am going to a bomb shelter. Russians continue to destruct my city
Good luck. Although I am a neighbor of Russia, may there be no war in the world
It does work AFAICT: Rust Playground
Maybe your code testing it has slice
of the wrong type? The error message mention &T1
and not &[…]
.
Well, the title of the thread is "address of a slice", and that's the method on slices for doing exactly what was requested: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_ptr