4

I am learning Rust as a beginner. I'm curious about how can we use numeric values as generics parameters that will be compiled at compile-time similar to template in C++

This is an equivalent C++ code.

template<class T, int dim>
struct vec {
    std::array<T, dim> data;
    vec(): data() {}
    vec(const vec<T, dim>& obj): data(obj.data) {}
    ~vec() {}
};
int main() {
    vec<float, 3> v3;
}

That code above will be compiled the same as

struct vec {
    std::array<float, 3> data;
    vec(): data() {}
    vec(const vec<float, 3>& obj): data(obj.data) {}
    ~vec() {}
};
int main() {
    vec v3;
}
1
  • 1
    Const generics are still unstable, as noticed below, but you can try macros. They are more powerful in Rust than in C++. Commented Jun 29, 2019 at 6:08

2 Answers 2

5

I believe you are looking for const generics, which have yet to land in stable Rust. You may find an example here using unstable Rust.

Sign up to request clarification or add additional context in comments.

2 Comments

Just for the record, const generics have been stabilized in 1.51.
Here is a link to a Rust blog discussion const generics: blog.rust-lang.org/2021/02/26/const-generics-mvp-beta.html
-8

You know what, we actually have generics in Rust!

I strongly suggest you read through "The Rust Programming Language", TRPL.

And your question can be answer in here.

You don't really needs the contructor and destructor in Rust. Rust will do it for you. TRPL provides a solid example.

Also, for vector, generic data type is already supported so you don't have to implement it yourself. Check this out.

1 Comment

"we actually have generics in Rust!" Yes but const generics are unstable, and not mentioned in the TRPL link you provided. Link only answer are also discouraged on SO. "You don't really need […] destructor in Rust" Well, yes you do! The default destructor might not be enough for some cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.