Skip to content

Implement as operator overload trait #6016

Closed

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 }

Activity

  1. emberian commented on Jun 22, 2013

    @emberian
    Contributor

    See #7080

  2. emberian commented on Jul 13, 2013

    @emberian
    Contributor

    (closing as dup)

  3. added a commit that references this issue on Sep 10, 2020
  4. added a commit that references this issue on Oct 9, 2020
  5. added a commit that references this issue on Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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