-
Book Overview & Buying
-
Table Of Contents
Rust for C++ Developers
By :
Generic programming is the practice of writing a single function or structure that can work with more than one set of types. C++ implements generic behavior with templates and the Standard Template Library or STL. Despite some syntactical similarities, Rust's approach to generic programming is quite different than C++. This can make it challenging to provide equivalent C++ code examples, but we'll still use them to illustrate concepts whenever it's practical.
The easiest place to start with generics is a structure. Let's extend the Vector3 type we've been working with to allow for the use of a different base type.
generic_vector3.rs
struct GenericVector3<T> {
x: T,
y: T,
z: T,
}
generic_vector3.cpp
template <typename T>
struct GenericVector3 {
T x;
T y;
T z;
};
The Rust syntax is a little more compact, but not much of a departure from...