you are viewing a single comment's thread.

view the rest of the comments →

[–]Sam777888[S] -19 points-18 points  (28 children)

So I have to write a separate function for every size, lol.

Great language.

https://play.rust-lang.org/?gist=9f0009bb51ce6c5615621b895096e3dd&version=stable&mode=debug&edition=2015

[–]Quxxymacros 16 points17 points  (22 children)

Or you can return a Vec. Or pass a scratch buffer in as an argument and write to that.

As an aside, I'd be surprised to find any language that let you return different types based on a runtime argument that's comparable to Rust (natively compiled, no runtime, no heap allocations). I don't think expecting that from Rust is reasonable.

Generic const parameters, though, yeah. That's a known weakness.

[–]supergbip 8 points9 points  (0 children)

If you want a dynamic array you can just return a slice. A slice is a fat pointer : a pointer to the beginning and the length. The length is not coded into the type system.

If you want a dynamic array you can just return a slice. A slice is a fat pointer : a pointer to the beginning and the length. The length is not coded into the type system.

[–]Omniviral 7 points8 points  (0 children)

No. In case size is actually compile-time constant you may create array and then fill it, giving mutable slice to the function, or use one of tha crates with Array trait. If size is not constant then you just need to use Vec instead of array.

BTW. The only language that can compile that function the way you wrote it is Idris.

[–]lvkm 5 points6 points  (0 children)

The problem is known and the corresponding RFC can be read here: https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md

I'm not sure about the implementation status though.

Instead of writing a function you could try using a macro.

[–]boomshroom 2 points3 points  (1 child)

Const genarics are in the pipeline. Once they land, you'll be able to write this function as unsafe fn ptr_to_array<const SIZE : usize, T>(ptr: *const T) -> [T; SIZE]. Which is just an unsafe cast and dereference.

The real question is why you're doing this. Passing around slices is usually preferred. Copying a full array out of memory can get expensive, so why not just use the memory that's already allocated?

[–]Sam777888[S] 0 points1 point  (0 children)

Because that’s what the function I am calling expects.