Struct with reference member or struct with copy/clone member


#1

Hello

As I am new to Rust, I still have some issues to decide between reference or copy member in struct.
Here the problem I am trying to have a generic way to address structure like Array, hashmap, Serie, … etc.


use std::collections::*;
use std::hash::*;
use std::ops::Deref;

type Int = i32;
type Real = f64;
type Size = usize;


trait TensorBackend {
    type K;
    type V;
    fn size(&self) -> Size;
}

struct Tensor<'a, T: TensorBackend + 'a> {
    backend: &'a T
}

trait AsTensor<T :TensorBackend> {
    fn asTensor(&self) -> Tensor<T>;
}

impl <C: TensorBackend> AsTensor<C> for C {
    fn asTensor(&self) -> Tensor<C> {
        Tensor{ backend :self }
    }
}

impl<'a, T :TensorBackend + 'a> Deref for Tensor<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.backend
    }
}

impl <K :Eq + Hash, V :Clone> TensorBackend for HashMap<K, V> {
    type K = K;
    type V = V;
    
	fn size(&self) -> Size {
		self.len() as Size
	}
}

use std::ops::Add;

impl <'a, V2, C: TensorBackend + 'a> Add<V2> for Tensor<'a, C> {
	type Output = Tensor<'a, C>;
	
	fn add(self, rhs: V2) -> Self::Output {
        println!("add");
        self
    } 
}

My question is that if it is better to define Tensor struct with reference member or with a copy / clone like this:


struct Tensor<T: TensorBackend> {
    backend: T
}
 

Thank you in advance for help.