简体   繁体   English

可选的函数参数,指定为特征而不是具体类型

[英]Optional function argument that is specified as a trait instead of a concrete type

I have been watching Rust for the past few months but I just started into an actual project. 过去几个月我一直在看Rust,但我刚刚开始实际项目。 I am not sure if the terminology in the title is correct. 我不确定标题中的术语是否正确。 Please let me know how it can be corrected. 请告诉我如何纠正它。

I am writing a rust wrapper around the ENet library ( http://enet.bespin.org ). 我正在ENet库( http://enet.bespin.org )周围写一个防锈包装器。 My goal is to keep the rust API as similar to the C API as possible except to refactor functions that take C style handle pointers into member functions of structure objects. 我的目标是使rust API与C API保持尽可能类似,除了重构将C样式处理指针的函数处理成结构对象的成员函数。 I want to keep the API similar so that the official C documentation will apply equally well to the rust wrapper. 我想保持API类似,以便官方C文档同样适用于防锈包装器。

ENet exposes a single function to create either a client host or a server host. ENet公开单个函数以创建客户端主机或服务器主机。 When creating a server you pass a pointer to an IP Address structure to the function. 创建服务器时,将指向IP地址结构的指针传递给该函数。 When creating a client you pass NULL. 创建客户端时,传递NULL。

I am trying to emulate that behavior using the ToSocketAddr trait and Option but I am running into problems using them in conjunction. 我试图使用ToSocketAddr trait和Option来模拟该行为,但我遇到了使用它们的问题。

This is a reduced example of what I am trying to do: 这是我尝试做的一个简化示例:

use std::io::net::ip::ToSocketAddr;

fn create_host<A: ToSocketAddr>(addr: Option<A>) {
    match addr {
        Some(a) => println!("Address is {}. Return a server host object.",a.to_socket_addr()),
        None    => println!("no address... Return a client.")
    };
}


fn main() {
    create_host(Some("localhost:12345"));
    create_host(None);
}

The first call to create_host() works like a charm. 第一次调用create_host()就像一个魅力。 The second call however will not compile. 然而,第二个调用将无法编译。

Rustc returns Rustc回归

error: unable to infer enough type information about `_`; type annotations required

I am guessing that error is occurring because None doesn't provide any resolution to the generic A . 我猜测错误正在发生,因为None没有为通用A提供任何解决方案。 I tried the following but this doesn't work either because ToSocketAddr does not implement the trait core::kinds::Sized . 我尝试了以下但是这不起作用,因为ToSocketAddr没有实现trait core::kinds::Sized

fn create_host(addr: Option<ToSocketAddr>) {
    ...
}

Is there a way I can do this or do I need to take a different approach? 有没有办法可以做到这一点,还是我需要采取不同的方法?

fn main() {
    create_host(Some("localhost:12345"));
    create_host(None::<&str>);
}

I've chosen &str here as it is the same type as on the first call, so that the compiler wouldn't generate another monomorphized version of the generic function. 我在这里选择&str ,因为它与第一次调用时的类型相同,因此编译器不会生成泛型函数的另一个单形版本。 You could choose any type that implements ToSocketAddr . 您可以选择任何实现ToSocketAddr类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM