rust

Why can't I store a value and a reference to that value in the same struct?

梦想与她 提交于 2020-01-06 05:07:05
问题 I have a value and I want to store that value and a reference to something inside that value in my own type: struct Thing { count: u32, } struct Combined<'a>(Thing, &'a u32); fn make_combined<'a>() -> Combined<'a> { let thing = Thing { count: 42 }; Combined(thing, &thing.count) } Sometimes, I have a value and I want to store that value and a reference to that value in the same structure: struct Combined<'a>(Thing, &'a Thing); fn make_combined<'a>() -> Combined<'a> { let thing = Thing::new();

Is it possible to declare arrays without an explicit length? [duplicate]

北慕城南 提交于 2020-01-06 03:58:06
问题 This question already has an answer here : Can array lengths be inferred in Rust? (1 answer) Closed last year . In Rust, you can declare an array with a specific size: struct Vector(f64, f64); fn main() { let points: [Vector; 3] = [ Vector(1.0, 1.0), Vector(5.0, 5.0), Vector(0.0, 0.0), ]; println!("Length is {}\n", points.len()); } Is there a way to have the length ( 3 in this case) be implicit, since 3 elements are inside the array. Similar to how in C you can do: typedef double Vector[2];

Take slice of certain length known at compile time

醉酒当歌 提交于 2020-01-06 03:18:06
问题 In this code: fn unpack_u32(data: &[u8]) -> u32 { assert_eq!(data.len(), 4); let res = data[0] as u32 | (data[1] as u32) << 8 | (data[2] as u32) << 16 | (data[3] as u32) << 24; res } fn main() { let v = vec![0_u8, 1_u8, 2_u8, 3_u8, 4_u8, 5_u8, 6_u8, 7_u8, 8_u8]; println!("res: {:X}", unpack_u32(&v[1..5])); } the function unpack_u32 accepts only slices of length 4. Is there any way to replace the runtime check assert_eq with a compile time check? 回答1: Yes, kind of. The first step is easy:

How do I generate a text file during compile time and include its content in the output?

混江龙づ霸主 提交于 2020-01-05 11:49:54
问题 I'm trying to do almost the same as How to create a static string at compile time. build.rs use std::{env}; use std::path::Path; use std::io::{Write, BufWriter}; use std::fs::File; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("file_path.txt"); let mut f = BufWriter::new(File::create(&dest_path).unwrap()); let long_string = dest_path.display(); write!(f, "{}", long_string).unwrap(); } main.rs fn main() { static LONG_STRING: &'static str =

The example from the “chaining computations” section of the Tokio docs does not compile: “expected struct `std::io::Error`, found ()”

守給你的承諾、 提交于 2020-01-05 09:34:42
问题 I am learning Tokio. I read Getting asynchronous from the official docs, but the source code from the Chaining computations section cannot be compiled under the latest Rust version (Rust 2018, v1.31): extern crate tokio; extern crate bytes; #[macro_use] extern crate futures; use tokio::io::AsyncWrite; use tokio::net::{TcpStream, tcp::ConnectFuture}; use bytes::{Bytes, Buf}; use futures::{Future, Async, Poll}; use std::io::{self, Cursor}; // HelloWorld has two states, namely waiting to connect

What's the fastest way of finding the index of the maximum value in an array?

巧了我就是萌 提交于 2020-01-05 08:25:38
问题 I have a 2D array of type f32 (from ndarray::ArrayView2 ) and I want to find the index of the maximum value in each row, and put the index value into another array. The equivalent in Python is something like: import numpy as np for i in range (0, max_val, batch_size): sims = xp.dot(batch, vectors.T) # sims is the dot product of batch and vectors.T # the shape is, for example, (1024, 10000) best_rows[i: i+batch_size] = sims.argmax(axis = 1) In Python, the function .argmax is very fast, but I

When does type binding happen in Rust?

筅森魡賤 提交于 2020-01-05 07:50:11
问题 From what I know: In C language, the "type" of a variable is bound during compile time and the value of that variable is bound during run time. For example, in int a = 10; , the type int is bound to the variable a during compile time and the actual value 10 is bound (or assigned) to it during run time. But in Rust, we have let a = 2; . Here, when does the type (say i32 from any of the integer types in Rust) get bound to a ? I am building a front-end Rust compiler and am currently writing the

Why does matching on a tuple of dereferenced references not work while dereferencing non-tuples does?

百般思念 提交于 2020-01-05 07:44:20
问题 I'm trying to sort a Vec of enums. Please ignore the sorting mechanism itself, this is just a stripped-down example. use std::cmp::Ordering; enum MyEnum { Option1, Option2, } fn main() { let mut my_list: Vec<MyEnum> = vec![MyEnum::Option1, MyEnum::Option2, MyEnum::Option1]; // (1) - doesn't work my_list.sort_unstable_by(|a, b| match (*a, *b) { (MyEnum::Option1, MyEnum::Option1) => Ordering::Equal, (MyEnum::Option1, MyEnum::Option2) => Ordering::Less, _ => Ordering::Greater }); } I get the

Reference to unwrapped property fails: use of partially moved value: `self`

天大地大妈咪最大 提交于 2020-01-05 07:43:39
问题 I try to send an unwrapped string reference to a static method implemented for a struct. Here is a simplified code: fn main() { let a = A {p: Some("p".to_string())}; a.a(); } struct A { p: Option<String> } impl A { fn a(self) -> Self { Self::b(&self.p.unwrap()); self } fn b(b: &str) { print!("b: {}", b) } } It fails: error[E0382]: use of partially moved value: `self` --> src/main.rs:14:13 | 13 | Self::b(&self.p.unwrap()); | ------ value moved here 14 | self | ^^^^ value used here after move |

Syntax of Rust lifetime specifier

风格不统一 提交于 2020-01-05 07:38:10
问题 I need help understanding lifetime specifiers. I think I get the concept of lifetimes. I watched Memory, Ownership and Lifetimes. I just think if I could work through this small example it might help me with the syntax of lifetimes. A topic I, to date, find confusing. use std::collections::HashMap; fn main() { pub struct User<'a> { pub name: & 'a str } impl <'a>User<'a> { pub fn new(uname: & 'a str, pwd: & 'a str) -> User { User{name: uname} } } pub struct ChatRoom<'a> { pub name: & 'a str,