Binary operation by Vec


Hello!How can i add binary operations to Vec struct?Need inherited from Vec and define operations?
Thank you very much


You can’t add it directly to the Vec, since you don’t own the trait or the Vec, but you can wrap Vec in your own struct and implement it that way:

use std::ops::{Deref, DerefMut};

struct BinVec<T>(Vec<T>);

//Allows you to do Vec-stuff
impl<T> Deref for BinVec<T> {
    type Target = Vec<T>;
    fn deref(&self) -> &Vec<T> {

//Allows you to do mutable Vec-stuff
impl<T> DerefMut for BinVec<T> {
    fn deref_mut(&mut self) -> &mut Vec<T> {
        &mut self.0

//Implement your stuff here

fn main() {
    let mut v = BinVec(vec![]);
    for word in &*v {
        println!("{}", word);


Ok!Thank you very much!


No problem :slight_smile: By the way, you can actually implement traits directly for Vec if the trait is generic and you own the generic type, like in impl SomeonesTrait<MyType> for SomeonesType. One of your types or traits has to limit the implementation somehow to prevent conflicts.