简体   繁体   中英

How to return specialized type from associated function in generic structs?

I was trying to implement some kind of stack with a default type

pub struct Stack<T>(Vec<T>);

impl<T> Stack<T> {

  fn new() -> Self::<i32> {
    Self::<i32>(Vec::<i32>::new())
  }
}

However this won't compile, and gives an error like this:

error[E0109]: type arguments are not allowed for this type
 --> src\lib\stacks.rs:7:22
  |
7 |   fn new() -> Self::<i32> {
  |                      ^^^ type argument not allowed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0109`.
error: could not compile `nullptr`

Did I made any errors in this piece of code? Thank you.

Well, if you declared a generic <T> type stack, why would you try to force your new() method to always use a i32 ?

To make it really generic you should wait to pass its type only when instantiating:

pub struct Stack<T>(Vec<T>);

impl<T> Stack<T> {

  fn new() -> Self {
    Stack { 0: Vec::new() }
  }
}

fn main() {
    let x = Stack::<i32>::new(); // <- here
}

Besides that, the short way you've declared your struct struct Stack<T>(Vec<T>);will need you to use 0 to access the internal stack reference because you didn't give its field a name. It's up to you, but this way it would look a bit better:

pub struct Stack<T> {
    value: Vec<T>
}

impl<T> Stack<T> {

  fn new() -> Self {
    Stack { value: Vec::new() }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM