gpt4 book ai didi

types - 为什么在 Rust 函数中注释类型时会出现错误 "expected type argument"?

转载 作者:行者123 更新时间:2023-11-29 08:00:27 24 4
gpt4 key购买 nike

我正在研究 Rust 的 capnproto library .因为 Rust 在某些情况下可以推断类型,所以我可以这样做:

let mut message = ::capnp::message::Builder::new_default();

无需知道消息的类型。如果我想将对 message 的引用传递到一个函数中,我现在需要知道什么消息是让函数知道期望什么。

一般来说,有没有方便的方法来做到这一点?

到目前为止,我已经完成了以下工作:

let testing: () = message;

因编译器错误而失败:

error[E0308]: mismatched types
--> src/main.rs:197:18
|
197 | let temp: () = message;
| ^^^^^^^ expected (), found struct `capnp::message::Builder`

但是当我输入时,我的函数注释如下:

fn example_fn(message: capnp::message::Builder) {...}

我收到如下错误:

error[E0243]: wrong number of type arguments: expected 1, found 0
--> src/main.rs:72:32
|
72 | fn dump_capnp_to_file(message: capnp::message::Builder, filename: &str) {
| ^^^^^^^^^^^^^^^^^^^^^^^ expected 1 type argument

错误:由于先前的错误而中止

我是 C++ 背景的 Rust 新手;对不起,如果这是一个菜鸟问题!

最佳答案

Rust 不会在函数参数位置推断类型。这是设计使然,因为 Rust language FAQ状态:

Why aren't function signatures inferred?

In Rust, declarations tend to come with explicit types, while actual code has its types inferred. There are several reasons for this design:

  • Mandatory declaration signatures help enforce interface stability at both the module and crate level.

  • Signatures improve code comprehension for the programmer, eliminating the need for an IDE running an inference algorithm across an entire crate to be able to guess at a function’s argument types; it’s always explicit and nearby.

  • Mechanically, it simplifies the inference algorithm, as inference only requires looking at one function at a time.

capnp::message::Builder<A>采用类型参数 A ,您需要通过给出 A 来限定参数的类型一个值:

fn dump_capnp_to_file(message: capnp::message::Builder<SomeType>, filename: String) {
// ^^^^^^^^^^

或者让你的函数也通用,这样它就可以接受任何类型 A :

fn dump_capnp_to_file<A>(message: capnp::message::Builder<A>, filename: String) {
// ^^^ ^^^

限制 A

如果您选择最后一个选项,您可能需要额外的 trait bounds允许您使用 message 做不同的事情在函数里面。例如,您可能想要发送 message到另一个线程,这需要 Builder<A>实现 Send . Builder具有以下含义(reference):

impl <A> Send for Builder<A> where A: Send + Allocator

这意味着Builder<A>可以实现Send , 但仅当 A工具 SendAllocator .您可以在 A 上设置您自己的绑定(bind)(要求) :

fn dump_capnp_to_file<A>(message: capnp::message::Builder<A>, filename: String)
where A: Send + Allocator
{
// multi-threaded code...
}

或者(也许稍微好一点),绑定(bind) Builder<A>Send直接:

fn dump_capnp_to_file<A>(message: capnp::message::Builder<A>, filename: String)
where capnp::message::Builder<A>: Send

那么你只能调用dump_capnp_to_fileBuilder 上实现 Send .

关于types - 为什么在 Rust 函数中注释类型时会出现错误 "expected type argument"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com