代码之家  ›  专栏  ›  技术社区  ›  Raz Luvaton

如何在rust中使用结构泛型使用编译时已知大小为数组长度的类型

  •  0
  • Raz Luvaton  · 技术社区  · 1 年前

    我如何使用编译时已知大小的泛型( Sized )结构数组长度基于其大小

    我有以下错误:

    error: generic parameters may not be used in const operations
     --> src/lib.rs:4:43
      |
    4 |     arr: [Key; 1024 / std::mem::size_of::<Key>()]
      |                                           ^^^ cannot perform const operation using `Key`
      |
      = note: type parameters may not be used in const expressions
    

    对于以下代码

    Rust Playground

    type SomeKey = u64;
    
    // This does not work
    struct NotWorking<Key: Sized> {
        arr: [Key; 1024 / std::mem::size_of::<Key>()]
    }
    
    struct Working {
        arr: [SomeKey; 1024 / std::mem::size_of::<SomeKey>()]
    }
    
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Raz Luvaton    1 年前

    你目前无法稳定,它需要 #![feature(generic_const_exprs)] 因此每晚:

    #![feature(generic_const_exprs)]
    struct NotWorking<Key>
    where
        // this where clause is required to constrain the generic, once GCEs
        // are complete it's need might go away.
        [(); 1024 / std::mem::size_of::<Key>()]:,
    {
        arr: [Key; 1024 / std::mem::size_of::<Key>()],
    }
    
    推荐文章