Get alignment of unsized type?

Since align_of requires T: Sized, it doesn't work for unsized types. Is there any way to get the alignment of an unsized type?

I believe that Sized restriction is a bug, fortunately fixing it is not a breaking change. For now you can use Layout::for_value() and get alignment from it.

Yeah I should just get around to putting up a PR at some point. EDIT: Submitted this.

Unfortunately I don't have a value - just the type T. Any way with just the type?

Either of these should work for alignment:

  • for_value::<[T]>(&[])
  • for_value::<[T; 0]>(&[])

Edit: Those transitively require Sized, so actually no.

Unfortunately this is in a generic context (actually in a macro, where all I have is a $t:ty variable), so I can't rely on being able to construct instances of the type like &[].

The problem with ?Sized in this case is trait objects. What should align_of::<dyn Debug>() return, for instance?


Oh wait.. align_of_val() doesn't have Sized requirement. My bad, no API bugs. dyn Traits can store different underlying types with different alignments so you can only determine its alignment at runtime.

1 Like

With nightly, there's align_of_val_raw which you can give a pointer, if you have a way to create one of those. If you don't know the pointer metadata, though, it's impossible in a generic context.

My bad, I didn't think of the transitive requirements, derp.

Unsized types can have an alignment only known at runtime. For example when using trait objects.

RFC 3319 is proposing an Aligned trait, covering T: Sized and also DSTs with [T]. Trait objects would still be excluded.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.