rust

Extend lifetime of variable

倖福魔咒の 提交于 2020-01-19 14:13:26
问题 I'm trying to return a slice from a vector which is built inside my function. Obviously this doesn't work because v 's lifetime expires too soon. I'm wondering if there's a way to extend v 's lifetime. I want to return a plain slice, not a vector. pub fn find<'a>(&'a self, name: &str) -> &'a[&'a Element] { let v: Vec<&'a Element> = self.iter_elements().filter(|&elem| elem.name.borrow().local_name == name).collect(); v.as_slice() } 回答1: You can't forcibly extend a value's lifetime; you just

Why does cloning my custom type result in &T instead of T?

时光怂恿深爱的人放手 提交于 2020-01-19 14:11:13
问题 use generic_array::*; // 0.12.3 use num::{Float, Zero}; // 0.2.0 #[derive(Clone, Debug)] struct Vector<T, N: ArrayLength<T>> { data: GenericArray<T, N>, } impl<T, N: ArrayLength<T>> Vector<T, N> where T: Float + Zero, { fn dot(&self, other: Self) -> T { self.data .iter() .zip(other.data.iter()) .fold(T::zero(), |acc, x| acc + *x.0 * *x.1) } fn length_sq(&self) -> T { self.dot(self.clone()) } } error[E0308]: mismatched types --> src/lib.rs:21:18 | 21 | self.dot(self.clone()) | ^^^^^^^^^^^^

actix rust actor 框架学习 二 ping actor demo 代码

点点圈 提交于 2020-01-18 17:25:44
以下是官方文档的学习,了解基本的actix actor 编程模型 项目初始化 cargo 创建 cargo new actor-ping --bin 效果 ├── Cargo.toml └── src └── main.rs 添加依赖 cargo.toml 配置 [package] name = "actor-ping" version = "0.1.0" authors = ["rongfengliang <1141591465@qq.com>"] edition = "2018" ​ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html ​ [dependencies] actix = "0.8" ​ 创建Actor trait actor 代码 use actix::prelude::*; ​ struct MyActor { count: usize, } ​ impl Actor for MyActor { type Context = Context<Self>; } 说明 每个actor 必须有一个context,后边会有介绍 定义消息 消息是actor 可以接受的数据,消息是任何实现 Message trait 的类型 use

Rust入坑指南:亡羊补牢

 ̄綄美尐妖づ 提交于 2020-01-18 03:56:20
如果你已经开始学习Rust,相信你已经体会过Rust编译器的强大。它可以帮助你避免程序中的大部分错误,但是编译器也不是万能的,如果程序写的不恰当,还是会发生错误,让程序崩溃。所以今天我们就来聊一聊Rust中如何处理程序错误,也就是所谓的“亡羊补牢”。 基础概念 在编程中遇到的非正常情况通常可以分为三类:失败、错误、异常。 Rust中用两种方式来消除失败:强大的类型系统和断言。 对于类型系统,熟悉Java的同学应该比较清楚。例如我们给一个接收参数为int的函数传入了字符串类型的变量。这是由编译器帮我们处理的。 关于断言,Rust支持6种断言。分别是: assert! assert_eq! assert_ne! debug_assert! debug_assert_eq! debug_assert_ne! 从名称我们就可以看出来这6种断言,可以分为两大类,带debug的和不带debug的,它们的区别就是assert开头的在调试模式和发布模式下都可以使用,而debug开头的只可以在调试模式下使用。再来解释每个大类下的三种断言,assert!是用于断言布尔表达式是否为true,assert_eq!用于断言两个表达式是否相等,assert_ne!用于断言两个表达式是否不相等。当不符合条件时,断言会引发线程恐慌(panic!)。 Rust处理异常的方法有4种:Option、Result<T,

Cannot move out of borrowed content for a struct

僤鯓⒐⒋嵵緔 提交于 2020-01-17 12:27:09
问题 I'm trying to implement deserializer for a BERT data which comes from an another program via sockets. For the following code: use std::io::{self, Read}; #[derive(Clone, Copy)] pub struct Deserializer<R: Read> { reader: R, header: Option<u8>, } impl<R: Read> Read for Deserializer<R> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.reader.read(buf) } } impl<R: Read> Deserializer<R> { /// Creates the BERT parser from an `std::io::Read`. #[inline] pub fn new(reader: R) -

Linking AVR programs with Cargo

懵懂的女人 提交于 2020-01-17 07:18:22
问题 I have a Rust project which I am currently compiling and linking by hand: rustc --target=avr-atmel-none src/main.rs --emit=obj -o _build/main.rs.o -C opt-level=3 avr-gcc -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/main.rs.o avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex I would like to automate this with Cargo, so I started by setting avr-gcc as the linker, by adding the following to .cargo/config : [build] target = "avr-atmel-none" [target.avr-atmel-none

Rust's .o file format not recognized by GCC

时间秒杀一切 提交于 2020-01-17 06:54:21
问题 I'm trying to build a simple application in C that calls Rust functions, in Windows, using MinGW with GCC 4.9.3 and Rust 1.9.0 stable. Here's the source code: test.rs #![crate_type = "staticlib"] #[no_mangle] pub extern "C" fn get_number() -> isize { 42 as isize } main.c #include <stdio.h> int get_number(); int main() { printf("Hello, world!\n"); printf("Number is %d.\n", get_number()); return 0; } Now, I know I should use C-compatible types in Rust and whatnot. But before going into program

How to write a macro in Rust to match any element in a set?

拟墨画扇 提交于 2020-01-17 04:58:08
问题 In C, I'm used to having: if (ELEM(value, a, b, c)) { ... } which is a macro with a variable number of arguments to avoid typing out if (value == a || value == b || value == c) { ... } A C example can be seen in Varargs `ELEM` macro for use with C. Is this possible in Rust? I assume it would use match . If so, how would variadic arguments be used to achieve this? 回答1: macro_rules! cmp { // Hack for Rust v1.11 and prior. (@as_expr $e:expr) => { $e }; ($lhs:expr, $cmp:tt any $($rhss:expr),*) =>

OpenSSL crate fails compilation on Mac OS X 10.11

梦想与她 提交于 2020-01-17 03:07:50
问题 I tried to install the Iron framework for Rust on Mac OS X 10.11.2, but it failed when I run cargo build or cargo run on compiling openssl 's stuff: failed to run custom build command for `openssl-sys-extras v0.7.4` Process didn't exit successfully: `/xxx/rust/hello/target/debug/build/openssl-sys-extras-413d6c73b37a590d/build-script-build` (exit code: 101) --- stdout TARGET = Some("x86_64-apple-darwin") OPT_LEVEL = Some("0") PROFILE = Some("debug") TARGET = Some("x86_64-apple-darwin") debug

How do I reuse code for similar yet distinct types in Rust?

早过忘川 提交于 2020-01-16 20:19:40
问题 I have a basic type with some functionality, including trait implementations: use std::fmt; use std::str::FromStr; pub struct MyIdentifier { value: String, } impl fmt::Display for MyIdentifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.value) } } impl FromStr for MyIdentifier { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(MyIdentifier { value: s.to_string(), }) } } This is a simplified example, real code would be more complex. I want