Skip to content

CHANGE: Allow Fill to be implemented for third-party types #1650

@andresovela

Description

@andresovela

Today I learned that it is not possible to implement Fill for third-party types, in the form of [T].

I ran into this when I tried implementing Fill for [half::f16] (See f16)

error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
  --> /home/andy/dev/projects/half-rs/src/rand_distr.rs:96:1
   |
96 | impl rand::Fill for [f16] {
   | ^^^^^^^^^^^^^^^^^^^^-----
   |                     |
   |                     this is not defined in the current crate because slices are always foreign
   |
   = note: impl doesn't have any local type before any uncovered type parameters
   = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
   = note: define and implement a trait or new type instead

Note that I was trying to open a PR on the half crate to implement Fill for f16 and bf16.

Details

I opened a thread in URLO and someone suggested that this would be feasible if the function signature of fill was:

trait Fill {
    fn fill(_: &mut [Self], _: &mut impl Rng);
}

Motivation

It is currently not possible to implement this trait for third party types. If I wanted to have Fill implemented for half::f16, I'd have to add half as a dependency on rand, and gate it with a half feature. This doesn't scale.

Alternatives

Fill my [f16] using a different API? However, in my case, I'm working with APIs whose function signature looks like this

fn do_something<T: rand::Fill>(value: &mut T)

which still has the same issue, even I filled the [f16] with a different API.

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