-
-
Save rust-play/31c5cc428edb50e44114aacb73dd32ed to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
/// Simple Vector struct that implements a generic From trait. | |
#[derive(Clone)] | |
pub struct Vector<K> { | |
pub vector: Vec<K>, | |
} | |
/// From both [K; N] and Vec<K> | |
/// Preferably it should also work for &[K; N]. | |
impl<T: Into<Vec<K>>, K> From<T> for Vector<K> { | |
fn from(v: T) -> Self { | |
Vector { | |
vector: v.into(), | |
} | |
} | |
} | |
pub struct Matrix<K> { | |
pub matrix: Vec<Vector<K>>, | |
} | |
/// Only From [[K; M]; N] | |
impl<K: Clone, const N: usize, const M: usize> From<[[K; M]; N]> for Matrix<K> { | |
fn from(value: [[K; M]; N]) -> Self { | |
value.into_iter().map(Into::into).collect::<Vec<Vector<K>>>().into() | |
} | |
} | |
/// Only From Vec<Vector<K>> | |
impl<K: Clone> From<Vec<Vector<K>>> for Matrix<K> { | |
fn from(value: Vec<Vector<K>>) -> Self { | |
Matrix { | |
matrix:value.into_iter().collect() | |
} | |
} | |
} | |
/// I want to implement From for both Vec<Vector<K>> and [[K; M]; N] in the same | |
/// fashion as I have done for Vector<K>. However, this is not compiling. | |
/// Preferably it should also work for Vec<[K; M]>. | |
// impl<T: Into<Vec<Vector<K>>>, K> From<T> for Matrix<K> { | |
// fn from(v: T) -> Self { | |
// Matrix { | |
// matrix: v.into(), | |
// } | |
// } | |
// } | |
fn main() { | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_vector() { | |
// Works for [K; N]. | |
let v: Vector<f32> = Vector::from([]); | |
assert_eq!(v.vector, []); | |
let v = Vector::from([1., 2., 3.]); | |
assert_eq!(v.vector, [1., 2., 3.]); | |
// Works for Vec<K> | |
let v = Vector::from(vec![1., 2., 3.]); | |
assert_eq!(v.vector, [1., 2., 3.]); | |
// Does not work | |
let v = Vector::from(&[1., 2., 3.]); | |
assert_eq!(v.vector, [1., 2., 3.]); | |
} | |
#[test] | |
fn test_matrix() { | |
// Works for [[K; M]; N] | |
let m: Matrix<f32> = Matrix::from([[]]); | |
assert_eq!(m.matrix[0].vector, []); | |
let m: Matrix<f32> = Matrix::from([[1., 2., 3.]]); | |
assert_eq!(m.matrix[0].vector, [1., 2., 3.]); | |
// Works for Vec<Vector<K>> | |
let m: Matrix<f32> = Matrix::from(vec![Vector::from([1., 2., 3.])]); | |
assert_eq!(m.matrix[0].vector, [1., 2., 3.]); | |
// Does not work | |
let m: Matrix<f32> = Matrix::from(vec![[1., 2., 3.]]); | |
assert_eq!(m.matrix[0].vector, [1., 2., 3.]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment