相关疑难解决方法(0)

如何在Rust中匹配数据类型?

我正在尝试匹配结构的通用字段的数据类型并做出相应的反应.我的总体想法是这样的(代码不编译):

struct Foo<T> {
    bar: T,
}

fn main() {
    let x = Foo::<String> {
        bar: "world".to_string(),
    };

    match x.bar {
        String => println!("It's a string!"),
        u32 => println!("It's a u32!"),
        _ => println!("Something else"),
    };

    println!("end of program!");
}
Run Code Online (Sandbox Code Playgroud)

来自的错误消息x:

warning: unreachable pattern
  --> src/main.rs:12:9
   |
11 |         String => println!("It's a string!"),
   |         ------ matches any value
12 |         u32 => println!("It's a u32!"),
   |         ^^^ unreachable pattern
   |
   = note: `#[warn(unreachable_patterns)]` on by default

warning: …
Run Code Online (Sandbox Code Playgroud)

rust

10
推荐指数
1
解决办法
4785
查看次数

为什么枚举需要额外的内存大小?

我的理解是,enum就像union在C中一样,系统将在枚举中分配最大的数据类型.

enum E1 {
    DblVal1(f64),
}

enum E2 {
    DblVal1(f64),
    DblVal2(f64),
    DblVal3(f64),
    DblVal4(f64),
}

fn main() {
    println!("Size is {}", std::mem::size_of::<E1>());
    println!("Size is {}", std::mem::size_of::<E2>());
}
Run Code Online (Sandbox Code Playgroud)

为什么E1按预期占用8个字节,但E2占用16个字节?

rust

7
推荐指数
2
解决办法
2445
查看次数

是否可以在Rust中对泛型进行编译时类型检查?

我不想检查类型是否具有某种特征,但是我希望能够区分结构和整数。由于结构体和整数都可以实现相同的特征,因此我不知道如何区分它们。

之所以要这样做,是因为我正在使用serde_json将泛型类型转换为JSON,但我希望将其转换为JSON Object(在它为结构时发生),但不应将其转换为其他任何内容(例如JSON I64)。由于结构和整数都可以实现Serialize特征,因此无法区分它们。

目前,我让进程感到恐慌是因为它不是可以从中恢复的错误,但是由于我可能在编译时就知道这一点,所以我想知道在编译阶段是否有任何机制可以确定类型。

我想知道如何区分类型的“种类”而不是特征。

types rust

5
推荐指数
1
解决办法
735
查看次数

是否可以在Rust中使用多种类型进行模式匹配?

好像你不能.如果没有,是否有计划支持添加它或运行时类型信息(RTTI)?

struct Bus;
struct Car;
struct Person;

fn main() {
    let x = Bus;
    //or more realistically, let x = function_with_multiple_return_types();

    match x {
        Car => {
            // ...
        }
        Bus => {
            // this gets executed
        }
        Person => {
            // ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个例子很简单.在现实生活中,只有x多种类型才有用.例如let x = function_with_multiple_return_types();.

pattern-matching rust

3
推荐指数
1
解决办法
3076
查看次数

标签 统计

rust ×4

pattern-matching ×1

types ×1