rust

Can we get the source code location of the caller in a procedural macro attribute?

可紊 提交于 2020-04-07 05:19:45
问题 I have requirement to get the source location of the caller of every method. I am trying to create a proc_macro_attribute to capture the location and print it. #[proc_macro_attribute] pub fn get_location(attr: TokenStream, item: TokenStream) -> TokenStream { // Get and print file!(), line!() of source // Should print line no. 11 item } #[get_location] fn add(x: u32, y: u32) -> u32 { x + y } fn main() { add(1, 5); // Line No. 11 } 回答1: Ready to use solutions are available (see @timotree 's

Can we get the source code location of the caller in a procedural macro attribute?

拜拜、爱过 提交于 2020-04-07 05:18:18
问题 I have requirement to get the source location of the caller of every method. I am trying to create a proc_macro_attribute to capture the location and print it. #[proc_macro_attribute] pub fn get_location(attr: TokenStream, item: TokenStream) -> TokenStream { // Get and print file!(), line!() of source // Should print line no. 11 item } #[get_location] fn add(x: u32, y: u32) -> u32 { x + y } fn main() { add(1, 5); // Line No. 11 } 回答1: Ready to use solutions are available (see @timotree 's

Is it possible to match against the result of a `const fn`?

ぃ、小莉子 提交于 2020-04-07 05:07:46
问题 I've tried the naive approach fn main() -> Result<(), Box<std::error::Error>> { let num = 0; match num { u64::max_value() => println!("Is u64::max_value()"), _ => println!("Is boring") } Ok(()) } but it fails with expected tuple struct/variant, found method <u64>::max_value . Is there another syntax except n if n == u64::max_value() => ... which can I use? 回答1: The left part of => must be a pattern, and few expressions are also valid patterns. A call-expression is not a valid pattern. Named

Return JSON with an HTTP status other than 200 in Rocket

邮差的信 提交于 2020-04-07 03:46:02
问题 I want my Rocket API to have a route like this: #[post("create/thing", format = "application/json", data="<thing>")] When the client sends { "name": "mything" } , everything should be alright and I know how to do that, but when it sends { "name": "foo" } it should respond with something like this: HTTP/1.1 422 Unprocessable Entity Content-Type: application/json { "errors": [ { "status": "422", "title": "Invalid thing name", "detail": "The name for a thing must be at least 4 characters long."

Return JSON with an HTTP status other than 200 in Rocket

心不动则不痛 提交于 2020-04-07 03:44:12
问题 I want my Rocket API to have a route like this: #[post("create/thing", format = "application/json", data="<thing>")] When the client sends { "name": "mything" } , everything should be alright and I know how to do that, but when it sends { "name": "foo" } it should respond with something like this: HTTP/1.1 422 Unprocessable Entity Content-Type: application/json { "errors": [ { "status": "422", "title": "Invalid thing name", "detail": "The name for a thing must be at least 4 characters long."

Is there a way to simplify converting an Option into a Result without a macro?

半世苍凉 提交于 2020-04-07 02:37:01
问题 I have something like this (the real function is Ini::Section::get from rust-ini): impl Foo { pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str> where K: Hash + Eq, { // ... } } I have to call it several times: fn new() -> Result<Boo, String> { let item1 = match section.get("item1") { None => return Result::Err("no item1".to_string()), Some(v) => v, }; let item2 = match section.get("item2") { None => return Result::Err("no item2".to_string()), Some(v) => v, }; } To remove code bloat, I

Is there a way to simplify converting an Option into a Result without a macro?

家住魔仙堡 提交于 2020-04-07 02:35:44
问题 I have something like this (the real function is Ini::Section::get from rust-ini): impl Foo { pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str> where K: Hash + Eq, { // ... } } I have to call it several times: fn new() -> Result<Boo, String> { let item1 = match section.get("item1") { None => return Result::Err("no item1".to_string()), Some(v) => v, }; let item2 = match section.get("item2") { None => return Result::Err("no item2".to_string()), Some(v) => v, }; } To remove code bloat, I

From and Into traits and conversion of usize to f64

天涯浪子 提交于 2020-04-06 18:17:57
问题 I've been trying to write some Rust code in a very generic way, without specifying the types explicitly. However, I arrived at a point where I need to convert a usize to a f64 and this doesn't work. Presumably, f64 does not have enough precision to hold a an arbitrary usize value. When compiling on the nightly channel I get an error message: error: the trait `core::convert::From<usize>` is not implemented for the type `f64` [E0277] . What is the alternative, then, if I want to write the code

From and Into traits and conversion of usize to f64

白昼怎懂夜的黑 提交于 2020-04-06 18:16:56
问题 I've been trying to write some Rust code in a very generic way, without specifying the types explicitly. However, I arrived at a point where I need to convert a usize to a f64 and this doesn't work. Presumably, f64 does not have enough precision to hold a an arbitrary usize value. When compiling on the nightly channel I get an error message: error: the trait `core::convert::From<usize>` is not implemented for the type `f64` [E0277] . What is the alternative, then, if I want to write the code

Rust入坑指南:居安思危

£可爱£侵袭症+ 提交于 2020-04-06 09:29:18
Rust入坑指南:居安思危 任何事情都是相对的,就像Rust给我们的印象一直是安全、快速,但实际上,完全的安全是不可能实现的。因此,Rust中也是会有不安全的代码的。 严格来讲,Rust语言可以分为Safe Rust和Unsafe Rust。Unsafe Rust是Safe Rust的超集。在Unsafe Rust中并不会禁用任何的安全检查,Unsafe Rust出现的原因是为了让开发者可以做一些更加底层的操作。这些事情本身也是不安全的,如果仍然要进行Rust的安全检查,那么就无法进行这些操作。 在进行下面这5种操作时,Unsafe Rust不会进行安全检查。 解引用原生指针 调用unsafe的函数或方法 访问或修改可变的静态变量 实现unsafe的trait 读写联合体中的字段 基础语法 Unsafe Rust的关键字是unsafe,它可以用来修饰函数、方法和trait,也可以用来标记代码块。 标准库中也有不少函数是unsafe的。例如String中的from_utf8_unchecked()函数。它的定义如下: pub unsafe fn from_utf8_unchecked(bytes: Vec) -> String { String { vec: bytes } } 这个函数被标记为unsafe的原因是函数并没有检查传入参数是否是合法的UTF-8序列。也就是提醒使用者注意