是否有可能在Rust中特化无特征的泛型?

问题描述 投票:0回答:1

我来自C ++背景,我正在尝试将我以前写的一个程序翻译成Rust,主要是出于学习目的。

问题是这样的:我需要通过某些库读取一些二进制数据,并且有两种情况:

  1. 数据是字符串
  2. 数据是其他任何东西(任何整数)

在C ++中,我只是简单地专门设计一个模板,如果在编译时某些东西不可行/不可访问,它只会给出编译错误。例如,如果我在解决所有问题后调用不存在的函数。

我正试图在Rust中实现相同目标,这是我的MCVE代码。可以在playground here上找到。

fn main() {
    let _x: TheStruct<String> = TheStruct::new();
}

#[warn(dead_code)]
struct TheStruct<T> {
    val: T,
}

impl<T> TheStruct<T> {
    // so this is a function that is supposed to call two possible implementations if T is a string or T is something else
    fn new() -> Self {
        // This call is supposed to chooses the impl below based on time
        TheStruct::<T>::make_one()
    }
}

// this is String impl
impl TheStruct<String> {
    fn make_one() -> Self {
        TheStruct::<String> {
            val: String::new(),
        }
    }
}

// this is "everything else" impl
impl<T> TheStruct<T> {
    fn make_one() ->Self {
        TheStruct {
            std::Default::default()
        }
    }
}

如何在Rust中实现这一目标?我非常感谢帮助我进行编译。

[我还要指出,对于String和其他类型,某些实现应相同。我的意思是:我不想专门研究everything,即String的所有方法。

generics rust template-specialization generic-programming compile-time
1个回答
0
投票

Rust中的泛型比C ++中的模板更严格,关于如何定义类型。在这种情况下,如果不使用特征就不能定义泛型。如果T类型应该具有default方法,那么它必须反映在类型约束中。

因此TheStruct的正确含义如下:

impl<T : Default> TheStruct<T> {
    fn make_one() ->Self {
        TheStruct {
            val: T::default()
        }
    }
}

据我所知,Rust中不允许使用部分声明。因此,您无法同时声明TheStruct<String>TheStruct<Default>

© www.soinside.com 2019 - 2024. All rights reserved.