#Implementing `From<T>` where `T` is `Borrow`

24 messages · Page 1 of 1 (latest)

idle token
#
pub struct Mesh {
    pub positions: Option<Vec<Vec3>>,
    pub indices: Option<Vec<u32>>,
    pub uv: Option<Vec<Vec2>>,
    pub colors: Option<Vec<U8Vec4>>
}

pub trait MeshBuilder {
    fn build_mesh(&self) -> Mesh;
}

impl<T: Borrow<impl MeshBuilder>> From<T> for Mesh {
    fn from(mesh_builder: T) -> Self {
        mesh_builder.build_mesh()
    }
}

I want to express that for any type T that implements MeshBuilder, T, &T, &mut T etc. can be converted to Mesh, but this gives me:

error[E0207]: the type parameter `impl MeshBuilder` is not constrained by the impl trait, self type, or predicates
  --> src/mesh.rs:16:16
   |
16 | impl<T: Borrow<impl MeshBuilder>> From<T> for Mesh {
   |     

and

error[E0119]: conflicting implementations of trait `std::convert::From<mesh::Mesh>` for type `mesh::Mesh`
  --> src/mesh.rs:16:1
   |
16 | impl<T: Borrow<impl MeshBuilder>> From<T> for Mesh {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> std::convert::From<T> for T;

Is there no way to use the Borrow trait to do this all in one impl block?

broken gull
#

or even an Into

#

building from a reference also sounds kinda dubious btw

#

given there are a lot of Vecs in the Mesh

idle token
#

A MeshBuilder would be like something that stores the radius of a sphere, and it can be used to generate a Mesh, so it would only contain a single f32, for example

broken gull
#

ok

#

you should stay away from From then

#

this isn't what From is for, it's for translating the same object from one type to another.
like 7u8 -> 7i32 or Box<[7]> -> vec![7]

idle token
#

So should I just use MeshBuilder directly?

broken gull
#

yep

#

what made you want to use From ?

idle token
#

Is this because the semantics of From that the object should be the same?

broken gull
#

yes

idle token
broken gull
#

you might want to read this

broken gull
#

nice for error conversion

#

and different types that can represent the same thing

idle token
#

I thought I might want to use Into<Mesh> as a parameter

broken gull
#

i can understand that

#

i would advise to just use Mesh

#

impl Into and Impl AsRef sound really cool