Copy is not implemented for String

code first:

toml dependencies:
downcast-rs = "1.2"

use std::{any::{Any, TypeId}, fmt::{Debug, Display}};
use downcast_rs::Downcast;
use std::clone::Clone;

fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
    TypeId::of::<String>() == TypeId::of::<T>()
}

trait N:Downcast+Debug+Display{
    fn convert<T: 'static + Copy>(&self)->T;
}

impl N for String {
    fn convert<T: 'static + Copy>(&self)->T {
        *self.as_any().downcast_ref::<T>().unwrap()
    }
}

fn dosome(c :impl N)->String{                      //the parameter c:impl N cannot be changed because I also have any other types parameter for here.
    // I wannt to throw in string parameter and do something else, finally return something.(here retuan string for example.)
    let mut finalstr:String = "none".to_string();
    if is_string(&c){
        finalstr = c.convert::<String>();
    }
    finalstr
}

fn main() {
    let a:String = "A".to_string();
    let c = dosome(a);
    println!("final str: {}", &c);
}

I wrote above code but it warns: Copy is not implemented for String.
I tried the Clone but remain the same problem.
is there any other method to avoid this warning?

How about this?

use downcast_rs::Downcast;
use std::clone::Clone;
use std::{
    any::{Any, TypeId},
    fmt::{Debug, Display},
};

fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
    TypeId::of::<String>() == TypeId::of::<T>()
}

trait N: Downcast + Debug + Display {
    fn convert<T: 'static>(&self) -> &T;
}

impl N for String {
    fn convert<T: 'static>(&self) -> &T {
        self.as_any().downcast_ref::<T>().unwrap()
    }
}

fn dosome(c: impl N) -> String {
    if is_string(&c) {
        c.convert::<String>().to_string()
    } else {
        "none".to_string()
    }
}

fn main() {
    let a: String = "A".to_string();
    let c = dosome(a);
    println!("final str: {}", &c);
}
3 Likes

perfect,,, now I know the &T and T deeper....,
so intereestingggggggggg ,,,, thanks so much alice,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.