rustgd / cgmath

A linear algebra and mathematics library for computer graphics.
https://docs.rs/cgmath
Apache License 2.0
1.12k stars 155 forks source link

Implement From instead of Into for array/tuple/mint conversions #528

Closed agausmann closed 3 years ago

agausmann commented 3 years ago

Fixes missing impls of impl From<ArrayN> for ForeignType which is currently provided as impl Into<ForeignType> for ArrayN

From the std::convert::Into documentation:

One should avoid implementing Into and implement From instead. Implementing From automatically provides one with an implementation of Into thanks to the blanket implementation in the standard library.

While it isn't very significant, as you can write cgmath_vector.into() in most places, it makes code cleaner where type inference is not possible (e.g. format! macros):

// With `Into`: 
<Vector2<f32> as Into<[f32; 2]>>::into(a_vector)

// ... versus with `From`:
<[f32; 2]>::from(a_vector)

(Example adapted from this real code snippet that I had to write)

agausmann commented 3 years ago

(WIP, did a more thorough search and missed some impls)

kvark commented 3 years ago

I'm surprised Rust lets you do this, honestly. You are implementing From, which is a foreign trait for this crate, for stuff like std or mint types, which are also foreign for this crate. Why does it let you do this?

agausmann commented 3 years ago

Because the signature of the impl is more than just the trait and the type you are implementing. In impl ForeignTrait<LocalType> for ForeignType - the presence of the LocalType in the trait's generic parameter is also considered when evaluating orphan rules.

kvark commented 3 years ago

I do wonder if this is something that changed in Rust recently (in recent years, that is). It's nice that it works though :)