rust

[The RUST Programming Language]Chapter 4. Understanding Ownership (1)

无人久伴 提交于 2020-01-11 15:19:38
Understanding Ownership What Is Ownership? 什么是所有权? Ownership Rules 所有权规则 Variable Scope 变量作用域 The `String` Type `String`类型 Memory and Allocation 内存分配 Ways Variables and Data Interact: Move 变量和数据的交互方法:移动 Ways Variables and Data Interact: Clone 变量和数据的交互方法:克隆 Stack-Only Data: Copy 栈数据:复制 Ownership and Functions 所有权和函数 Return Values and Scope 返回值和作用域 所有权是Rust最独特的一个特性,它可以让Rust在没有垃圾回收的情况下保证内存的安全性。因此,理解所有权在Rust中的工作原理是非常重要的。在本章中,我们将讨论所有权和几个与它相关的特性:借用、切片以及Rust如何在内存中存放数据。 What Is Ownership? 什么是所有权? Rust的核心特性是 ownership 所有权,尽管这个特性非常直白,易于解释,但它对Rust这门语言有非常深远的影响。 所有程序在运行时,都须要管理它们使用到的内存。有些语言有垃圾回收的机制

cannot borrow variable as mutable because it is also borrowed as immutable while building a self-referential HashMap

时光总嘲笑我的痴心妄想 提交于 2020-01-11 13:21:13
问题 I'm trying to build a self-referential HashMap : use std::collections::HashMap; struct Node<'a> { byte: u8, map: HashMap<i32, &'a Node<'a>>, } fn main() { let mut network = HashMap::<u32, Node>::new(); network.insert(0, Node { byte: 0, map: HashMap::<i32, &Node>::new() }); network.insert(1, Node { byte: 1, map: HashMap::<i32, &Node>::new() }); let zeroeth_node = network.get(&0).unwrap(); let mut first_node = network.get_mut(&1).unwrap(); first_node.map.insert(-1, zeroeth_node); } I'm running

How can I get a reference to the key and value immediately after inserting into a `HashMap`?

…衆ロ難τιáo~ 提交于 2020-01-11 12:34:25
问题 use std::collections::HashMap; use std::collections::hash_map::Entry::*; fn hook(k: &str, v: &str) {} fn tt(k: String, v: String) -> Option<String> { let mut a: HashMap<String, String> = HashMap::new(); match a.entry(k) { Occupied(mut occupied) => { let old = occupied.insert(v); //hook(&k, &old); Some(old) } Vacant(vacant) => { let v = vacant.insert(v); let k = vacant.key(); // Why doesn't it work? //hook(&k, v); None } } } I would like to call hook immediately after a key is inserted into

Get a random character from a string and append to another string

♀尐吖头ヾ 提交于 2020-01-11 12:32:15
问题 I'm trying to write the Rust equivalent of the following C++ code: result += consonants[rand() % consonants.length()]; It is meant to take a random character from the string consonants and append it to the string result . I seem to have found a working Rust equivalent, but it's... monstrous, to say the least. What would be a more idiomatic equivalent? format!("{}{}", result, consonants.chars().nth(rand::thread_rng().gen_range(1, consonants.chars().count())).unwrap().to_string()); 回答1: A few

How to make a request with client certificate in Rust

蓝咒 提交于 2020-01-11 11:36:11
问题 I have a project with microservices deployed in Bluemix with Docker containers. All microservices are written in Java and the communication is using JKS files. I also developed a microservice in Node.js with Express.js. To consume the other microservices, I used the Request module with option.agentOptions feature and a pfx file , like this: var options = { uri: config.get("https://www.example.com/ms/service"), method: 'POST', body: data, json: true, headers: { 'Content-Type': 'application

How does Rust handle killing threads?

痞子三分冷 提交于 2020-01-11 10:41:47
问题 Is there a parent-child connection between threads that are spawned? If I kill the thread from where I spawned other threads, are those going to get killed too? Is this OS specific? 回答1: How does Rust handle killing threads? It doesn't; there is no way to kill a thread. See also: How to terminate or suspend a Rust thread from another thread? How to check if a thread has finished in Rust? Is there a parent-child connection between threads that are spawned? When you spawn a thread, you get a

Is there an easy way to cast entire tuples of scalar values at once?

烂漫一生 提交于 2020-01-11 10:34:30
问题 I want to cast a (u16, u16) to a (f32, f32) . This is what I tried: let tuple1 = (5u16, 8u16); let tuple2 = tuple1 as (f32, f32); Ideally, I would like to avoid writing let tuple2 = (tuple1.0 as f32, tuple1.1 as f32); 回答1: There's no built-in way to do this, but one can do it with a macro: macro_rules! tuple_as { ($t: expr, ($($ty: ident),*)) => { { let ($($ty,)*) = $t; ($($ty as $ty,)*) } } } fn main() { let t: (u8, char, isize) = (97, 'a', -1); let other = tuple_as!(t, (char, i32, i8));

How do I run a project's example using Cargo?

心已入冬 提交于 2020-01-11 10:23:12
问题 I'm trying to run the example code from this project. Following the instructions on the Cargo docs, I did the following: git clone https://github.com/basiliscos/rust-procol-ftp-client cd rust-procol-ftp-client cargo run cargo test cargo test should also have compiled the example according to the Rust docs. Although cargo test executes successfully, when I change into the target/debug directory, I don't find an executable for ftp-get (which is the example code). The target/debug/examples

How can I convince the borrow checker to allow me to cache values?

北战南征 提交于 2020-01-11 10:21:48
问题 The borrow checker beat me: use std::collections::HashMap; struct Cache { cache: Vec<HashMap<String, String>>, } impl Cache { fn get(&mut self, index: usize, key: String) -> String { let mut cache = &mut self.cache[index]; match cache.get(&key) { Some(r) => { return r.clone(); } None => { let r = "foo".to_string(); // something smart here cache.insert(key, r.clone()); return r; } } } } What I get: error[E0502]: cannot borrow `*cache` as mutable because it is also borrowed as immutable --> src

How can I convince the borrow checker to allow me to cache values?

落爺英雄遲暮 提交于 2020-01-11 10:21:47
问题 The borrow checker beat me: use std::collections::HashMap; struct Cache { cache: Vec<HashMap<String, String>>, } impl Cache { fn get(&mut self, index: usize, key: String) -> String { let mut cache = &mut self.cache[index]; match cache.get(&key) { Some(r) => { return r.clone(); } None => { let r = "foo".to_string(); // something smart here cache.insert(key, r.clone()); return r; } } } } What I get: error[E0502]: cannot borrow `*cache` as mutable because it is also borrowed as immutable --> src