rust

Rust学习笔记003-变量与可变性

余生颓废 提交于 2020-02-05 00:20:01
变量声明 语法格式: let 变量名: 变量类型 = 变量值; let var: i32 = 123; 有几点要注意: 以关键字 let 开头,类型一定跟在冒号 : 后面; 变量必须先声明,初始化后才能使用; 初始化 Rust中,每个变量必须被合理的初始化后才能被使用。使用未初始化的变量,不能被编译通过。 let x: i32; println!("x = {}", x); //运行报错:use of possibly-uninitialized `x` 编译器会帮我们做一个执行路径的静态分析,确保变量在使用前一定被初始化。 let x: i32; //声明x,不使用mut修饰 if 条件 { x = 123; //初始化x,这里不用使用mut修饰,因为这是初始化吗,不是修改 println!("x = {}", x); } //如果条件不满足,则x未被初始化 //但是只要下面不适用x就不会报错 可变性 Rust中变量默认是不可变的,比如下面运行会报错: let x: i32 = 123; x = 456; //运行报错:cannot assign twice to immutable variable 如果想让变量可写,可以使用关键字 mut 。 let mut x: i32 = 123; x = 456; 此时,变量才是可读写的。 实际上, let 语句在这里引入了模式解构,

Can match on Result here be replaced with map_err and “?”

送分小仙女□ 提交于 2020-02-04 11:45:42
问题 I have some code which looks like this (greatly simplified version). A function takes two function arguments of type LoadClient and CheckApproval and returns either an error or a string. pub struct Client { pub id: String, } pub enum MyErr { RequiresApproval(Client, String), LoadFailed, } pub fn authorize<LoadClient, CheckApproval>(load_client: LoadClient, check_approval: CheckApproval) -> Result<String, MyErr> where LoadClient: FnOnce(String) -> Result<Client, String>, CheckApproval: for<'a>

How do I use a macro defined in another crate?

。_饼干妹妹 提交于 2020-02-04 05:46:06
问题 I've seen a couple tutorials to create a Python module using the cpython crate but still have errors when building: extern crate cpython; use cpython::{PyObject, PyResult, Python, PyTuple, PyDict, ToPyObject, PythonObject}; fn add_two(py: Python, args: &PyTuple, _: Option<&PyDict>) -> PyResult<PyObject> { match args.as_slice() { [ref a_obj, ref b_obj] => { let a = a_obj.extract::<i32>(py).unwrap(); let b = b_obj.extract::<i32>(py).unwrap(); let mut acc:i32 = 0; for _ in 0..1000 { acc += a + b

How to insert HashMap into PostgreSQL as JSON type?

旧巷老猫 提交于 2020-02-04 05:37:07
问题 contacts has a data structure as HashMap , I'm using PostgreSQL client -rust-postgres to insert contact 's key and value into a table, then I want to select from the table. Below is what I tried so far. I need help with writing the right syntax. use postgres::{Client, NoTls}; use std::collections::HashMap; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut client = Client::connect("host=127.0.0.1 user=postgres", NoTls)?; client.simple_query(" DROP TABLE IF EXISTS following_relation

HRTB: Concrete type bounded by a trait containing lifetime type parameter vs bounded by only a lifetime type parameter

一世执手 提交于 2020-02-04 03:58:26
问题 This is actually an offshoot of this SO question. Consider the following code: trait Trait<'b> { fn func(&'b self) {} } struct Struct {} impl<'s> Trait<'s> for Struct {} fn test<'s, T:'s>(t: T) where T: Trait<'s>, { t.func(); } It fails, as the compiler sees that t lives for less than the 's and 's is set by the caller (i.e longer than the stack-frame of the func ) and traits are invariant over type parameters. However, if I introduce HRTB (Higher Rank Trait Bounds) here, the code compiles:

Is there a way to obtain elided lifetime parameters from the Rust compiler?

依然范特西╮ 提交于 2020-02-04 02:40:53
问题 Given a Rust program, which compiles correctly, can I get the compiler to tell me what the elided lifetimes were inferred to be? 回答1: The cases where the compiler (currently 1 ) can allow elided lifetimes are actually so simple that there isn't much the compiler could tell you about what it inferred: Given a function, all elided lifetimes have the same value. The compiler doesn't accept elided lifetimes in cases where it would have a choice to make. The exception is in methods, but tying all

When is it required to use lifetimes?

我们两清 提交于 2020-02-04 01:10:31
问题 I have read up on lifetimes and understood that every single variable binding has a lifetime. It seems as though, however, that I cannot think of a time you would actually need to use them, considering the compiler does quite a great worl at inferring them when necessary. The Rust book, I have read. I would like an example that is simple to understand, even for someone like myself! 回答1: We use lifetime parameters in Rust when a variable (that has some lifetime) refers to another variable with

How to get executable's full target triple as a compile-time constant without using a build script?

自古美人都是妖i 提交于 2020-02-04 00:56:10
问题 I'm writing a Cargo helper command that needs to know the default target triple used by Rust/Cargo (which I presume is the same as host's target triple). Ideally it should be a compile-time constant. There's ARCH constant, but it's not a full triple. For example, it doesn't distinguish between soft float and hard float ARM ABIs. env!("TARGET") would be ideal, but it's set only for build scripts, and not the lib/bin targets. I could pass it on to the lib with build.rs and dynamic source code

How to borrow the T from a RefCell<T> as a reference?

坚强是说给别人听的谎言 提交于 2020-02-03 15:25:50
问题 Sometimes I have a struct containing a value which is wrapped in a RefCell , and I want to borrow the value, but I don't want to make the signature of the accessor function to depend on the internal implementation. To make it work, I need to return the reference as a Ref<T> instead of a &T . For example, if this is my struct: use std::cell::RefCell; pub struct Outer<T> { inner: RefCell<T>, } I could write an accessor like this: use std::cell::Ref; impl<T> Outer<T> { fn get_inner_ref(&self) ->

How to borrow the T from a RefCell<T> as a reference?

孤者浪人 提交于 2020-02-03 15:25:28
问题 Sometimes I have a struct containing a value which is wrapped in a RefCell , and I want to borrow the value, but I don't want to make the signature of the accessor function to depend on the internal implementation. To make it work, I need to return the reference as a Ref<T> instead of a &T . For example, if this is my struct: use std::cell::RefCell; pub struct Outer<T> { inner: RefCell<T>, } I could write an accessor like this: use std::cell::Ref; impl<T> Outer<T> { fn get_inner_ref(&self) ->