< 返回版块

LJason77 发表于 2021-02-28 19:32

类似这种:

struct A;
struct B;

let a = get_vec(A);
let b = get_vec(B);

fn get_vec<T>(T) -> Vec<T> {
  let s: Vec<T> = Vec::new();
  // Do something
  // s.push(something)
  s
}

Vec<> 这里是需要具体的 struct


已解决,感谢各位回答,感谢 whfuyn 大佬的方法:

struct A;
struct B;

fn main() {
    let a: Vec<A> = get_vec::<A>();
    let b: Vec<B> = get_vec::<B>();
}

fn get_vec<T>() -> Vec<T> {
  let s: Vec<T> = Vec::new();
  // Do something
  // s.push(something)
  s
}

评论区

写评论
vimcdoe 2021-02-28 19:53
#[derive(Debug)]
struct A;

#[derive(Debug)]
struct B;

fn main() {
    let a = get_vec(A);
    dbg!(a);

    let b = get_vec(B);
    dbg!(b);
}
fn get_vec<T>(v: T) -> Vec<T> {
    let mut s = Vec::new();
    s.push(v);
    s
}
whfuyn 2021-02-28 19:46
struct A;
struct B;

fn main() {
    let a: Vec<A> = get_vec::<A>();
    let b: Vec<B> = get_vec::<B>();
}

fn get_vec<T>() -> Vec<T> {
  let s: Vec<T> = Vec::new();
  // Do something
  // s.push(something)
  s
}

Playgroud

sstudioer 2021-02-28 19:42

用宏实现;

1 共 3 条评论, 1 页