我有这种格式的代码:
fn f(n: usize) -> Result<Vec<usize>, String> {
...
if some_runtime_condition {
return Err("failure".to_string()); // LINE A
}
let mut v = Vec::with_capacity(n);
while v.len() < n { // THE EXPENSIVE LOOP
... // complex logic building v
}
Ok(v)
}
Run Code Online (Sandbox Code Playgroud)
当我将 A 行更改为
return Err(format!("failure on {}", n)); // LINE A
调试(在发布模式下),我发现格式化错误字符串几乎花费了 0 时间,相反循环速度慢了 30-40%。据我了解,A 行的两个版本(就循环而言)之间唯一重要的区别是我使用格式字符串在当前范围内的堆上分配了其他数据。
我能够通过将代码更改为以下内容来解决性能问题并保留格式字符串:
#[inline(never)]
fn the_loop(n) -> Vec<usize> {
let mut v = Vec::with_capacity(n);
while v.len() < n { // THE EXPENSIVE LOOP …Run Code Online (Sandbox Code Playgroud) 假设我有一个与数据成员密切相关的通用逻辑以及一段抽象逻辑。如何在不为每个实现重写相同代码的情况下用 Rust 类型编写它?
这是我可能在 Scala 中编写的内容的一个玩具示例。请注意,抽象类具有依赖于数据成员name和抽象逻辑的具体逻辑formatDate()。
abstract class Greeting(name: String) {
def greet(): Unit = {
println(s"Hello $name\nToday is ${formatDate()}.")
}
def formatDate(): String
}
class UsaGreeting(name: String) extends Greeting {
override def formatDate(): String = {
// somehow get year, month, day
s"$month/$day/$year"
}
}
class UkGreeting(name: String) extends Greeting {
override def formatDate(): String = {
// somehow get year, month, day
s"$day/$month/$year"
}
}
Run Code Online (Sandbox Code Playgroud)
这只是一个玩具示例,但我现实生活中的限制是:
name)。我已经创建了一个 EC2 实例,但我似乎无法访问我在其上启动的服务(例如在 port 上1234)。实例是
我已在该实例上启动了一个服务器,并验证我可以从我的计算机或同一子网中的另一个 EC2 实例httpd通过端口访问该服务器。80我还验证了我可以localhost:1234从原始 EC2 实例进行卷曲。
但Failed to connect to $MY_IP port 1234: Connection refused每当我尝试从我的机器或同一子网中的其他 EC2 实例(尝试私有和公共 IP)获取端口时,就会出现这种情况。什么可能仍然阻止请求?我怎样才能开始调试?
我已经浏览过类似的答案,但我的安全组应该已经允许此流量。

我试图在 Rust 中实现一个流,以便在 tonic GRPC 处理程序中使用,但遇到了这个困难:大多数创建流的方法没有易于表达的类型,但我需要实现的 GRPC 特征需要特定的 Stream 类型。像这样(简化):
// trait to implement
trait GrpcHandler {
type RespStream: futures::Stream<ResponseType> + Send + 'static
fn get_resp_stream() -> Self::RespStream;
}
// a start at implementing it
impl GrpcHandler for MyHandler {
type RespStream = ???; // what do I put here?
fn get_resp_stream() -> Self::RespStream {
futures::stream::unfold((), |_| async {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Some((ResponseType {}, ()))
})
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我的流的类型在技术上类似于Unfold<(), ComplicatedFnSignatureWithImpl, ComplicatedFutureSignatureWithImpl>,但即使我输入了整个内容,编译器也不会因为它是不透明类型而感到高兴。我如何引用该流的类型?
我的目标是为各种类型(时间戳,日期等)配备他们默认可能没有的好的属性(订购, - 等).我正在做这样的事情:
trait NiceProperties[T] {
def -(t: T): Double
def +(d: Double): T
...
}
implicit class BetterTimestamp(val t: Timestamp) extends NiceProperties[Timestamp] {
override def -(Timestamp): ...
}
Run Code Online (Sandbox Code Playgroud)
这一切都正常,直到我需要将它传递给一个假定的函数NiceProperties:
def myUtil[T](t: NiceProperties[T]): T = {
(t + 1.0) + 1.0
}
Run Code Online (Sandbox Code Playgroud)
这现在失败了,因为函数缺少隐式证据表明类T可以隐式向上转换NiceProperties[T],所以它不能添加(t + 1.0): T到double.
有没有办法将隐式类的证据传递给函数?或者,有更好的模式吗?
对于一个玩具示例,假设我想为磁盘上的文件创建缓存并记录其输出。这是我希望能发挥作用的:
struct Cache {
data: HashMap<String, String>
}
impl Cache {
fn load(&mut self, filename: &str) -> String {
let result = match self.data.get(filename) {
Some(s) => s.clone(),
None => {
let s = fs::read_to_string(filename).expect("couldn't read");
self.data.insert(String::from(filename), s.clone());
return s;
}
};
println!("my result: {}", result);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
但该None => {...}子句不像它自己的函数那样执行,因此它return退出整个load函数。我尝试了几种不同的方法,但无法让多行匹配子句返回值。有什么方法可以让这种类型的matchRust 工作吗?
Rust 版本:1.50.0 语言版本:2018
假设我想要一个train可以随时在两个轨道之一之间切换并u8在其当前位置写入 a 的轨道。天真地是这样的:
struct Train<'a> {
track_a: &'a mut [u8],
track_b: &'a mut [u8],
current_track: &'a mut [u8], // either track_a or track_b
idx: usize,
}
impl<'a> Train<'a> {
pub fn new(track_a: &'a mut [u8], track_b: &'a mut [u8]) -> Self {
Self {
track_a,
track_b,
idx: 0,
current_track: track_a,
}
}
pub fn toggle_track(&mut self) {
if self.current_track == self.track_a {
self.current_track = self.track_b;
} else {
self.current_track = self.track_a;
}
}
pub fn write(&mut …Run Code Online (Sandbox Code Playgroud) rust ×5
abstract ×1
amazon-ec2 ×1
connection ×1
heap-memory ×1
implicit ×1
opaque-types ×1
performance ×1
scala ×1
traits ×1