Skip to content

Impl Copy for Range #2848

Closed
Closed
@jyn514

Description

@jyn514

From rust-lang/rust#48649 (closed as needing an RFC): It would be nice for Range<Idx: Copy> to implement Copy.

I want to store a Range in a struct, but that prevents me from making the struct Copy. I can make a (start, end) struct that wraps it but that seems a little silly.

With Range from the standard library (playground):

use core::ops::Range;

// error[E0204]: the trait `Copy` may not be implemented for this type
#[derive(Copy)]
struct HasRange {
    r: Range<usize>,
    other_field: usize,
}

// works fine
struct HasRangeWrapper {
    r: RangeWrapper,
    other_field: usize,
}

#[derive(Copy, Clone)]
pub struct RangeWrapper {
    start: usize,
    end: usize,
}

// Note that Range is isomorphic to RangeWrapper;
// you can convert freely between the two
impl From<Range<usize>> for RangeWrapper {
    fn from(range: Range<usize>) -> Self {
        Self { start: range.start, end: range.end }
    }
}

impl From<RangeWrapper> for Range<usize> {
    fn from(range: RangeWrapper) -> Self {
        Self { start: range.start, end: range.end }
    }
}

There is more discussion of pros and cons in the rust-lang/rust issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Idea

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions