Skip to content

Implement as operator overload trait #6016

Closed
@brendanzab

Description

@brendanzab

Proposed trait for inclusion in core::ops:

#[lang="cast"]
trait Cast<T> {
    fn cast(&self) -> T;
}

Example implementation:

impl Cast<f32> for float { fn cast(&self) -> f32 { self as f32 } }
impl Cast<int> for f32   { fn cast(&self) -> int { self as int } }

impl<T: Cast<U>, U> Cast<Vec3<U>> for Vec3<T> {
    fn cast(&self) -> Vec3<U> {
        Vec3 { x: self.x as U, y: self.y as U, z: self.z as U }
    }
}

type Vec3f   = Vec3<float>;
type Vec3f32 = Vec3<f32>;
type Vec3i   = Vec3<int>;

fn main() {
    let a = Vec3 { x: 1f, y: 1f, z: 1f };
    let b = a as Vec3f32;
    let c = b as Vec3i;
}

Perhaps there could be a deriving attribute as well:

#[deriving(Cast)]
struct Vec3<T> { x: T, y: T, z: T }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions