0
votes

Which traits and markers have to be implemented on a generic type T so that it could be send over channels? The Type T shall not contain any references and own all its contents its 'pure' from any reference (so it is guaranteed to be owned by its scope only). The same is true for all of T's nested fields. So that no lifetime specifier would be required, to transfer ownership. Which traits does i32 implement, that my genric type T does not implement to prevent the error fn from compiling?

fn error<T: Send+Sized>(mut data: Vec<T>)->Receiver<T>{
    let (s, r) = channel();
    std::thread::spawn(move ||{
        while let Some(nextthing) = data.pop(){
            s.send(nextthing);
        }
    });
    r
}

as opposed to

fn thisworks(mut data: Vec<i32>)->Receiver<i32>{
    let (s, r) = channel();
    std::thread::spawn(move ||{
        while let Some(nextthing) = data.pop(){
            s.send(nextthing);
        }
    });
    r    
}

Error: i just want it to work like for i32: The ownership is just cleanly transferred without questions for lifetimes (maybe has something to do with the Primitive type and i32's copy trait?)

rror[E0310]: the parameter type `T` may not live long enough
 --> src/main.rs:7:5
  |
5 | fn error<T: Send+Sized>(mut data: Vec<T>)->Receiver<T>{
  |          -- help: consider adding an explicit lifetime bound `T: 'static`...
6 |     let (s, r) = channel();
7 |     std::thread::spawn(move ||{
  |     ^^^^^^^^^^^^^^^^^^
  |
note: ...so that the type `[closure@src/main.rs:7:24: 11:6 data:std::vec::Vec<T>, s:std::sync::mpsc::Sender<T>]` will meet its required lifetime bounds
 --> src/main.rs:7:5
  |
7 |     std::thread::spawn(move ||{
  |     ^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0310`.
error: Could not compile `playground`.

The playground link is https://play.rust-lang.org/?version=nightly&mode=release&edition=2018&gist=117113384490f15bb33ff8f749661769

1
Sized is a default bound for generics; you don't need to write it explicitly.trentcl

1 Answers

0
votes

It's not about the type, it's about the lifetime of the type.

The compiler error was spot-on. The only change you require is this line:

fn error<T: Send+Sized+'static>(mut data: Vec<T>)->Receiver<T>{

This addition of 'static is an additional requirement that the type must not be ephemeral; i.e. it must be defined for the lifetime of the program. This does not mean that the object itself must have a 'static lifetime, just the type.