Structs from Abstract Struct Instance

Hi,
Does Rust allow creating Structs that are instances of more abstract structs? For a concrete example consider:

Abstract Struct: its instances would be binary strings of length n
BinaryString { size: u32 }
Concrete Struct (examples):
Keyspace { key: BinaryString(80) } -- the no. in brackets represents an instance of the BinaryString struct where size = 80
Message { m: BinaryString(160) }

If there's a roundabout way to do this, even that would help.

Thanks.

Maybe a generic constant is what you are after?

struct BinaryString<const SIZE: usize>();

struct Keyspace {
    key: BinaryString<80>,
}
3 Likes
struct BinaryString<const SIZE: usize>{}
struct Keyspace { key: BinaryString<80> } 
struct Message { key: BinaryString<80> } 

Maybe this is what you need?

2 Likes

Jinx :smile:

Thanks a lot! This is exactly what I needed. If it is covered in the Rust book, would it be possible to point out where this is?

I don't know about the book (and I'm on mobile right now) but the reference has a section about const generics that is quite thorough with good examples IMO:

https://doc.rust-lang.org/reference/items/generics.html#const-generics

Thank you for sharing :slight_smile:

1 Like

Hi, I was using this struct to perform a variety of tasks, one of them being a function which given BinarySpace<N> returns BinarySpace<N+1>. However, this task seems way more complicated than I thought, and I don't quite understand how else to proceed. Here's the relevant code:

Struct Definition:

struct BinarySpace<const N: usize> {
    value: [u8; N],
}

A wrapper function:

fn dlp_gen<const N: usize, const M: usize>(s: BinarySpace<N>) -> BinarySpace<M> {
    let p = 2u128.pow(89) - 1; // this is a prime number
    let g = 2u128.pow(27) - 1; // since p is a prime, all n < p are coprime to it.

    const N_: usize = N;
    const M_: usize = M + 1;
    dlp_gen_f::<N, {N+1}>(&s, &p, &g);
    unimplemented!();
}

which calls:

fn dlp_gen_f<const N: usize, const M: usize>(&s: BinarySpace<N>, p: &u128, g: &u128) -> BinarySpace<M>
{
    unimplemented!();
}

Thanks for any help!

This is not possible in stable Rust. const evaluation is very much an evolving part of the language. What you can do is, on nightly, opt into the (highly) experimental feature generic_const_exprs and do something like this:

#![feature(generic_const_exprs)]

struct BinarySpace<const N: usize> {
    value: [u8; N],
}

fn dlp_gen<const N: usize, const M: usize>(s: BinarySpace<N>) -> BinarySpace<M> where [(); N + 1]: {
    let p = 2u128.pow(89) - 1; // this is a prime number
    let g = 2u128.pow(27) - 1; // since p is a prime, all n < p are coprime to it.

    //const N_: usize = N;
    //const M_: usize = M + 1;
    dlp_gen_f::<N, {N+1}>(&s, &p, &g);
    unimplemented!();
}

fn dlp_gen_f<const N: usize, const M: usize>(s: &BinarySpace<N>, p: &u128, g: &u128) -> BinarySpace<M>
{
    unimplemented!();
}

Playground.

Thank you