我上周开始学习 Rust,通过阅读书籍和文章,同时尝试从其他语言转换一些代码。
我遇到了一种情况,我试图通过下面的代码来举例说明(这是我试图从另一种语言转换的简化版本):
#[derive(Debug)]
struct InvalidStringSize;
impl std::fmt::Display for InvalidStringSize {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "string is too short")
}
}
impl std::error::Error for InvalidStringSize {}
pub fn extract_codes_as_ints(
message: String,
) -> Result<(i32, i32, i32), Box<dyn std::error::Error>> {
if message.len() < 20 {
return Err(Box::new(InvalidStringSize {}));
}
let code1: i32 = message[0..3].trim().parse()?;
let code2: i32 = message[9..14].trim().parse()?;
let code3: i32 = message[17..20].trim().parse()?;
Ok((code1, code2, code3))
}
Run Code Online (Sandbox Code Playgroud)
所以基本上我想从给定字符串的特定位置提取 3 个整数(我也可以尝试检查其他字符的某些模式,但我已经忽略了该部分)。
我想知道,有没有办法同时“捕获”或验证解析调用的所有三个结果?我不想为每个添加匹配块,我只想检查是否有人导致错误,并在这种情况下返回另一个错误。说得通?
到目前为止,我能想到的唯一解决方案是创建另一个具有所有解析的函数,并匹配其结果。还有其他方法可以做到这一点吗?
另外,非常欢迎对代码其他部分的任何反馈/建议,我正在努力寻找在 Rust 中做事的“正确方法”。
当您使用函数 SSL_CTX_new 创建 SSL_CTX 时,您需要按照文档传递一个方法作为参数:
https://www.openssl.org/docs/ssl/SSL_CTX_new.html
所有方法都具有三种变体:通用方法、客户端方法和服务器方法。
例如,您有 TLSv1_method、TLSv1_server_method、TLSv1_client_method。
我的问题是:我什么时候应该使用特定的(客户端/服务器)方法?它们有什么用?我总是可以用通用方法进行交换吗?
基本上我有以下代码:
import multiprocessing
import time
class MyProcess(multiprocessing.Process):
def __init__(self, ):
multiprocessing.Process.__init__(self)
self.queue = multiprocessing.Queue()
def run(self):
print "Subprocess starting!"
time.sleep(4)
print "Subprocess exiting!"
def addToQueue(self):
starttime = time.time()
count=0
print "Adding stuff to queue..."
while time.time()-starttime < 4:
self.queue.put("string")
count += 1
print "Added %d objects!" % count
#self.queue.close()
if __name__ == "__main__":
process = MyProcess()
process.start()
print "Waiting for a while"
time.sleep(2)
process.addToQueue()
time.sleep(1)
print "Child process state: %d" % process.is_alive()
Run Code Online (Sandbox Code Playgroud)
主进程完成后,它不会退出.什么都没发生,它只是阻止.我发现戒烟的唯一方法是杀死它(不是SIGTERM,SIGKILL).
如果我使用该注释行,它会退出但发出IOError.
我查看了multiprocessing.queue的代码,它使用了另一个线程(threading.Thread)中生成的os.pipe().我怀疑是线程在写入管道时阻塞,并且当使用close()方法时,它会引发IOError.
所以我的问题是:有更清洁的方法来处理这个问题吗?
我的意思是,我有这种情况,一直在写一个队列.当接收进程退出(干净或不干净)时,我应该关闭队列并在发送方进程上获得IOError?
编辑:进程的输出
Waiting for …
Run Code Online (Sandbox Code Playgroud)