Skip to content

Allow crates defining type T to implement external traits for [T] #39328

@rnewman

Description

@rnewman

Scenario:

Expected:

  • I can implement Display for [T], just as I can for T, allowing third-party libraries to call Display-requiring methods with both slices and individual values.

Actual:

  • [T] is a type that isn't defined in my crate. Display is a trait that isn't defined in my crate. The compiler refuses to allow me to implement it.

Example playground:

https://is.gd/lLsx57https://is.gd/lLsx57

The stated workaround (from IRC; thanks talchas) is to define some kind of wrapper type, MySlice, that I own. This wrapper contains a reference to the real slice, and implements every necessary trait as a passthrough to the slice. That fixes the ownership of the type, allowing implementation of Display.

This workaround presupposes that it's possible to get the third-party library to accept a MySlice wherever it calls arbitrary traits, rather than it getting a &[T] out of something else. I haven't assessed whether that's feasible for something like combine, which naturally ends up taking sub-slices of inputs.

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