Sample StaticVectors with Distributions.jl

I need to generate some random vectors with a custom distribution, and I would like to use the Distributions.jl API. However, my vectors are small StaticVectors and sampling from a distribution returns plain Vectors.

As shown by @Elrod on Creating random Static Vector by StaticVector.jl and Distributions.jl in a loop, you can define a distribution using static vectors, but you still get dynamic vectors when sampling:

julia> using Distributions, StaticArrays
julia> dist2dN = MvNormal(@SVector([0., 0.]),10.0)
MvNormal{Float64, PDMats.ScalMat{Float64}, SVector{2, Float64}}(
dim: 2
μ: [0.0, 0.0]
Σ: [100.0 0.0; 0.0 100.0]
)
julia> rand(dist2dN)
2-element Vector{Float64}:
 -15.693466638813794
 -10.710701041361501

Is there a way to make rand(my_sampler) return an SVector or an MVector?

You could use the in-place function Random.rand! and store the result in a preallocated array. You could convert this preallocated array to an SVector without incurring allocations.

Upon further inspection, I realized that I didn’t actually need the Distributions.jl API. For my use case, it was better just to Generate random values of custom type (Julia stdlib).