Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

rust named tuple

/* A named tuple is its own new type, just with anonymous
 * fields like a regular tuple.
 * This is in contrast to type aliases that are simply
 * new names for the same type.
 */

// Named Tuple ==========================================
struct Vec2D(f32, f32);
struct Pos2D(f32, f32);
fn take_vec2d(vec: Vec2D) { }

// Type Alias ===========================================
type Vec3D = (f32, f32, f32);
type Pos3D = (f32, f32, f32);
fn take_vec3d(vec: Vec3D) { }

// ======================================================
fn main() {
    let vec2d = Vec2D(1., 1.);
    let pos2d = Pos2D(vec2d.0, vec2d.1);

    take_vec2d(vec2d); // works
    // take_vec2d(pos2d); // panics

    let vec3d: Vec3D = (1., 1., 1.);
    let pos3d: Pos3D = (vec3d.0, vec3d.1, vec3d.2);

    take_vec3d(vec3d); // works
    take_vec3d(pos3d); // works
}
 
PREVIOUS NEXT
Tagged: #rust #named #tuple
ADD COMMENT
Topic
Name
5+2 =