-1

I'm working on code like the following:

use std::cell::RefCell;

struct CallbackWithArgs<T> {
    callback: Box<Fn(&mut T) -> ()>,
    arg: RefCell<T>,
}

struct S {
    args: CallbackWithArgs<_>,
}

The compiler has an error:

error[E0121]: the type placeholder `_` is not allowed within types on item signatures
 --> src/main.rs:9:28
  |
9 |     args: CallbackWithArgs<_>,
  |                            ^ not allowed in type signatures

What is the correct way to do this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
framlog
  • 13
  • 4
  • 1
    Please also add the compiler error. – Neikos Jan 15 '18 at 08:19
  • 2
    "So could anyone enlighten me with the correct way to do this?" What is "this"? What is it that you want to do? – mcarton Jan 15 '18 at 08:22
  • 1
    Why would you not make `S` generic to allow any type? – EvilTak Jan 15 '18 at 09:22
  • The compiler error is something like `expect `std::any::Any + 'static`, found `std::any::Any``. Thus, after I set lifetime properly, this error has been fixed. I think the problem's gone. However, I'm still a little bewildered with the combination of lifetime and trait declaration in generic type declaration. – framlog Jan 15 '18 at 12:16
  • [*The Rust Programming Language*](https://doc.rust-lang.org/book/second-edition/) has an [*entire chapter*](https://doc.rust-lang.org/book/second-edition/ch10-00-generics.html) on generics. – Shepmaster Jan 15 '18 at 13:39

1 Answers1

3

You cannot use _ in a struct declaration; the compiler needs to know the struct's size at compile time.

If you want the type to be generic you can add a type parameter to S just as you did to CallbackWithArgs:

struct CallbackWithArgs<T> {
    callback: Box<Fn(&mut T) -> ()>,
    arg: RefCell<T>,
}

struct S<T> {
    args: CallbackWithArgs<T>,
}

Playground Link

For an explanation of _, see What is Vec<_>?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Neikos
  • 1,840
  • 1
  • 22
  • 35
  • Yeap, I know I can't use `_` in that place. I just wanna express the idea of `Any`. Thanks anyway. – framlog Jan 15 '18 at 12:13