rust - 如何根据泛型类型参数赋予不同的值?

标签 rust

我正在尝试通过遵循 TheChernoProject Series on openGL 来实现 VertexBufferLayout 结构.我一直很容易地将 C++ 系列改编为 Rust,但我被卡住了。

VertexBufferElement 有一个计数,它使用的 data_type 的 glEnum 和一个 bool 值,标准化。有一个名为 push 的通用方法,它采用 u32 计数,将 VertexBufferElement 推送到元素 Vec 并更新步幅。

我似乎无法获得接受代码以匹配类型的函数。当我遇到错误时,我尝试使用 TypeIdAnyPhantomData

pub fn push<T: 'a>(&mut self, count: u32) {
    let dt = TypeId::of::<T>();
    let (data_type, normalized) = if dt == TypeId::of::<i8>() {
        (gl::BYTE, false)
    } else if dt == TypeId::of::<u8>() {
        (gl::UNSIGNED_BYTE, true)
    } else if dt == TypeId::of::<i16>() {
        (gl::SHORT, false)
    } else if dt == TypeId::of::<u16>() {
        (gl::UNSIGNED_SHORT, false)
    } else if dt == TypeId::of::<i32>() {
        (gl::INT, false)
    } else if dt == TypeId::of::<u32>() {
        (gl::UNSIGNED_INT, false)
    } else if dt == TypeId::of::<f16>() {
        (gl::HALF_FLOAT, false)
    } else if dt == TypeId::of::<f32>() {
        (gl::FLOAT, false)
    } else if dt == TypeId::of::<f64>() {
        (gl::DOUBLE, false)
    } else {
        panic!("Incompatible Type")
    };
    self.elements.push(VertexBufferElement{data_type, count, normalized, _marker: PhantomData});
    self.stride += mem::size_of::<T>();
}

vertex_buffer_layout.rs

    error[E0310]: the parameter type `T` may not live long enough
  --> opengl\examples\vertex_buffer_layout.rs:26:18
   |
25 |     pub fn push<T: 'a>(&mut self, count: u32) {
   |                 -- help: consider adding an explicit lifetime bound `T: 'static`...
26 |         let dt = TypeId::of::<T>();
   |                  ^^^^^^^^^^^^^^^
   |
note: ...so that the type `T` will meet its required lifetime bounds
  --> opengl\examples\vertex_buffer_layout.rs:26:18
   |
26 |         let dt = TypeId::of::<T>();
   |  

起初它是 'T​​' 可能活得不够长,但它只是一个通用函数,而且 float 只指示一个保存的数字,而不是类型本身,所以我尝试了 PhantomData。之后的任何错误都是我不知道自己在做什么,之前从未使用过 PhantomData,并且找不到针对这种情况的任何信息。

最佳答案

按照编译器的建议对我来说效果很好:

help: consider adding an explicit lifetime bound T: 'static...

use std::any::TypeId;

enum Type {
    Byte,
    Short,
}

fn decide<T: 'static>() -> (Type, bool) {
    let dt = TypeId::of::<T>();

    if dt == TypeId::of::<u8>() {
        (Type::Byte, false)
    } else if dt == TypeId::of::<u16>() {
        (Type::Short, true)
    } else {
        panic!("Unknown type")
    }
}

fn main() {}

在 Rust 的 future 版本中,您可以使用 match 表达式来缩短它:

#![feature(const_type_id)]

fn decide<T: 'static>() -> (Type, bool) {
    const ID_U8: TypeId = TypeId::of::<u8>();
    const ID_U16: TypeId = TypeId::of::<u16>();

    match TypeId::of::<T>() {
        ID_U8 => (Type::Byte, false),
        ID_U16 => (Type::Short, true),
        _ => panic!("Unknown type"),
    }
}

但是,我宁愿不允许出现运行时故障:

enum Type {
    Byte,
    Short,
}

trait AsType {
    fn as_type() -> (Type, bool);
}

impl AsType for u8 {
    fn as_type() -> (Type, bool) {
        (Type::Byte, false)
    }
}

impl AsType for u16 {
    fn as_type() -> (Type, bool) {
        (Type::Short, true)
    }
}

fn main() {
    u8::as_type();   // Ok
    bool::as_type(); // Error
}
error[E0599]: no function or associated item named `as_type` found for type `bool` in the current scope
  --> src/main.rs:24:5
   |
24 |     bool::as_type();
   |     ^^^^^^^^^^^^^ function or associated item not found in `bool`
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `as_type`, perhaps you need to implement it:
           candidate #1: `AsType`

关于rust - 如何根据泛型类型参数赋予不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50584981/

相关文章:

asynchronous - 特征绑定(bind) `tokio::net::tcp::stream::TcpStream: tokio_io::async_read::AsyncRead` 不满足

module - 如何将 Rust 模块放在单独的文件中?

rust - 为什么我不允许转换包含特征关联类型的值?

rust - 是否可以使用泛型的类型参数来控制数组的大小?

rust - 为什么隐藏不释放借用的引用?

rust - 如何避免对 libssl.so.10 和 libcrypto.so.10 的依赖

rust - 为什么在实现 From<&[u8]> 时需要生命周期

rust - 是否有必要强制转换为 float 以访问 Rust 中的基本数学函数?

winapi - 为什么WNetOpenEnum会得到ERROR_INVALID_ADDRESS(487)结果?

rust - 使用非静态引用的方法静态声明的结构