考虑以下程序。
import asyncio
import multiprocessing
from multiprocessing import Queue
from concurrent.futures.thread import ThreadPoolExecutor
import sys
def main():
executor = ThreadPoolExecutor()
loop = asyncio.get_event_loop()
# comment the following line and the shutdown will work smoothly
asyncio.ensure_future(print_some(executor))
try:
loop.run_forever()
except KeyboardInterrupt:
print("shutting down")
executor.shutdown()
loop.stop()
loop.close()
sys.exit()
async def print_some(executor):
print("Waiting...Hit CTRL+C to abort")
queue = Queue()
loop = asyncio.get_event_loop()
some = await loop.run_in_executor(executor, queue.get)
print(some)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我只想在按“ CTRL + C”时正常关机。但是,执行程序线程似乎阻止了该操作(即使我确实致电shutdown)
在我看来,这NamedTuple和TypedDict相当相似,Python开发人员自己承认。
关于PEP,我宁愿添加有关NamedTuple和TypedDict的共同部分,它们非常相似,后者已经在结构上起作用。你怎么看? 资源
但是后来圭多对此不太确定。
我不确定NamedTuple和TypedDict是否真的一样(除非它们都试图在静态类型的世界中处理过时的模式)。
因此,这是我懒惰的尝试,目的是使其他人在官方文档似乎缺乏的情况下进行清晰的比较。
Rust 是否在幕后为每个对象使用某种类型的实例 ID,如果是这样,是否可以使其可见?
考虑这个
struct SomeStruct;
fn main() {
let some_thing = SomeStruct;
println!("{:UniqueId}", some_thing);
let another = some_thing;
println!("{:UniqueId}", another);
}
Run Code Online (Sandbox Code Playgroud)
我在这里使用伪格式字符串{:UniqueId}。在这种情况下,它可能会打印
struct SomeStruct;
fn main() {
let some_thing = SomeStruct;
println!("{:UniqueId}", some_thing);
let another = some_thing;
println!("{:UniqueId}", another);
}
Run Code Online (Sandbox Code Playgroud)
我知道 Rust 会按位复制,我想让它真正可见。如果我有这样的实例 ID,我可以通过比较 ID 使其可见。
不过,可能有另一种方法可以实现相同的目标。
我想编写一个get_members从GitHub团队返回成员的函数.
pub fn get_members(group_id: &str) -> Result<Vec<User>, Error> {
let client = Client::new();
let query = format!("https://api.github.com/teams/{}/members?access_token={}",
group_id,
config::get_env(config::ENV_TOKEN));
println!("{}", query);
let mut res = try!(client
.get(&query)
.header(UserAgent("my/app".to_owned()))
.send());
let mut body = String::new();
try!(res.read_to_string(&mut body));
try!(json::decode(&body));
}
Run Code Online (Sandbox Code Playgroud)
有两种不同类型的错误可供使用.一个是hyper::error::Error另一个是rustc_serialize::json::DecoderError.
我以为我可以使用工具From<::hyper::error::Error> for Error和From<rustc_serialize::json::DecoderError>.但由于io::Error我的箱子中没有其他两个错误也没有,我不允许遵循这种方法.
我想知道去这里的方式是什么.我是否需要提出自己的AppError类型然后From<>为此实现特征?这是要走的路吗?
Any为了更深入地了解Rust,我正在努力摆弄并投入.从C#我习惯了这样一个事实,即转换可能会导致运行时异常,因为在C#中进行转换基本上意味着亲爱的编译器,相信我,我知道我在做什么请将其转换成一个int32因为我知道它会起作用.
但是,如果您正在执行无效的转换,程序将在运行时以异常方式爆炸.所以我想知道(安全)Rust中的转换是否同样会导致运行时异常.
所以,我想出了这个代码来试一试.
use std::any::Any;
fn main() {
let some_int = 4;
let some_str = "foo";
{
let mut v = Vec::<&Any>::new();
v.push(&some_int);
v.push(&some_str);
// this gives a None
let x = v[0].downcast_ref::<String>();
println!("foo {:?}", x);
//this gives Some(4)
let y = v[0].downcast_ref::<i32>();
println!("foo {:?}", y);
//the compiler doesn't let me do this cast (which would lead to a runtime error)
//let z = v[1] as i32;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我的观察是编译器似乎阻止了我这种运行时异常,因为我必须通过downcast_ref哪个返回Option使得它再次安全.当然,我可以unwrap用它 …
我发誓我搜索了所有互联网,我努力去理解我发现的所有相似的答案.但是,我仍然无法理解这是否可行.
trait Foo {
fn do_foo (&self);
}
trait Bar {
fn do_bar (&self);
}
struct SomeFoo;
impl Foo for SomeFoo {
fn do_foo(&self) {
println!("doing foo");
}
}
struct SomeFooBar;
impl Foo for SomeFooBar {
fn do_foo(&self) {
println!("doing foo");
}
}
impl Bar for SomeFooBar {
fn do_bar(&self) {
println!("doing bar");
}
}
fn main () {
let foos:Vec<Box<Foo>> = vec!(Box::new(SomeFoo), Box::new(SomeFooBar));
for foo in foos {
foo.do_foo();
/*
if let Some(val) = foo.downcast_whatever<Bar>() {
val.bar();
}*/
} …Run Code Online (Sandbox Code Playgroud) 到处都写着读取element.offsetWidth会导致元素尺寸的重新计算(甚至回流?)。
然而,我正在努力让这种效果变得可见。
在 chrome 中,我希望能够通过 3 个简单的步骤使其可见:
$0.offsetWidth现在,如果我转到时间线选项卡,我会假设看到绘制的回流。然而,我什么也没看到。所以我一定是弄错了什么。
我有这个结构:
#[deriving(Clone)]
pub struct MiddlewareStack {
handlers: Vec<Box<Middleware + Send>>
}
Run Code Online (Sandbox Code Playgroud)
然后我有代码添加处理程序 handlers
pub fn utilize<T: Middleware>(&mut self, handler: T){
self.middleware_stack.add(handler);
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我想知道,为什么必须使用泛型?
所以我尝试了这个:
pub fn utilize(&mut self, handler: Middleware){
self.middleware_stack.add(handler);
}
Run Code Online (Sandbox Code Playgroud)
但这让我有这个错误:
error: reference to trait `Middleware` where a type is expected; try `Box<Middleware>` or `&Middleware`
pub fn utilize(&mut self, handler: Middleware){
Run Code Online (Sandbox Code Playgroud)
那好吧.特征不能直接用作参数(因为它们会被删除?).但那么为什么它们作为通用类型参数合法?
所以,我继续尝试:
pub fn utilize(&mut self, handler: Box<Middleware + Send>){
self.middleware_stack.add(handler);
}
Run Code Online (Sandbox Code Playgroud)
但这让我有以下错误:
error: failed to find an implementation of trait middleware::Middleware for Box<middleware::Middleware:Send>
self.middleware_stack.add(handler);
Run Code Online (Sandbox Code Playgroud)
所以,我想知道:那些代码真的必须使用泛型吗?不是,有一个特殊的原因,我不希望它不使用泛型.更多的是我想要理解为什么它必须使用泛型,因为来自诸如C#的Java之类的语言它可能只是一个非泛型方法,它使用接口作为参数,应该粗略地转换为Rust中的特征.
跟进弗拉基米尔的优秀答案 …
我有这个lib.rs文件.
use std::io::{ Result, Read };
pub trait ReadExt: Read {
/// Read all bytes until EOF in this source, returning them as a new `Vec`.
///
/// See `read_to_end` for other semantics.
fn read_into_vec(&mut self) -> Result<Vec<u8>> {
let mut buf = Vec::new();
let res = self.read_to_end(&mut buf);
res.map(|_| buf)
}
/// Read all bytes until EOF in this source, returning them as a new buffer.
///
/// See `read_to_string` for other semantics.
fn read_into_string(&mut self) -> …Run Code Online (Sandbox Code Playgroud) 我再次与生命斗争.或者实际上,我有点赢了这场比赛,但我不确定结果是否是预定的处理方式.
假设我有两个生命周期的结构:Inner<'a, 'b>.现在我想写一个定义new(inner: &Inner) -> Self方法的特征.实现者应该可以自由地将引用存储在Inner内部并定义其他方法来处理它.
我想出了这个(它有效!)但我有几个问题
struct Inner<'a, 'b>{
foo: &'a str,
bar: &'b str
}
trait Worker<'data, 'a, 'b> {
fn new (inner: &'data Inner<'a, 'b>) -> Self;
fn work_with_inner () { println!("works on inner");}
}
struct SomeWorker<'inner, 'a:'inner, 'b:'inner> {
inner: &'inner Inner<'a, 'b>
}
impl<'data, 'a, 'b> Worker<'data, 'a, 'b> for SomeWorker<'data, 'a, 'b> {
fn new (inner: &'data Inner<'a, 'b>) -> Self {
SomeWorker {
inner: inner
}
} …Run Code Online (Sandbox Code Playgroud)