rust

Why is `std::ptr::null` not usable with unsized types?

好久不见. 提交于 2020-05-14 19:16:12
问题 As I understand, the standard (only?) way to make a null pointer in Rust is std::ptr::null . However, that function is declared as follows. pub const fn null<T>() -> *const T In this declaration, T is implicitly assumed to have fixed size (otherwise, it would be T: ?Sized ). As a consequence, it is impossible to use this function with *const str or *const [u32] for example. test it in the playground Is there a good reason for excluding unsized types? What's wrong with wanting to create a null

How to sum the values in an array, slice, or Vec in Rust?

拟墨画扇 提交于 2020-05-14 19:16:10
问题 Editor's note: This question's example is from a version of Rust prior to 1.0 and references types and methods no longer found in Rust. The answers still contain valuable information. The following code let mut numbers = new_serial.as_bytes().iter().map(|&x| (x - 48)); let sum = numbers.sum(); results in the following error: std::iter::Map<,&u8,u8,std::slice::Items<,u8>>` does not implement any method in scope named `sum` What must I do to sum an array of bytes? The following works: for byte

In Rust, is “as” an operator?

坚强是说给别人听的谎言 提交于 2020-05-14 18:37:06
问题 The Rust Reference presently says the following about the as operator: 7.2.12.5 Type cast expressions A type cast expression is denoted with the binary operator as . Executing an as expression casts the value on the left-hand side to the type on the right-hand side. An example of an as expression: fn average(values: &[f64]) -> f64 { let sum: f64 = sum(values); let size: f64 = len(values) as f64; sum / size } (Also, since it will be relevant: 7.2.12.8 Operator precedence The precedence of Rust

How to tell the borrow checker that a cleared Vec contains no borrows? [duplicate]

瘦欲@ 提交于 2020-05-14 18:07:50
问题 This question already has answers here : Borrow checker doesn't realize that `clear` drops reference to local variable (6 answers) Closed 22 days ago . I'm processing a massive TSV (tab separated values) file and want to do this as efficiently as possible. To that end, I thought I'd prevent allocation of a new Vec for every line by pre-allocating it before the loop: let mut line = String::new(); let mut fields = Vec::with_capacity(headers.len()); while reader.read_line(&mut line)? > 0 {

When is tail recursion guaranteed in Rust?

陌路散爱 提交于 2020-05-14 16:44:26
问题 C language In the C programming language, it's easy to have tail recursion : int foo(...) { return foo(...); } Just return as is the return value of the recursive call. It is especially important when this recursion may repeat a thousand or even a million times. It would use a lot of memory on the stack . Rust Now, I have a Rust function that might recursively call itself a million times: fn read_all(input: &mut dyn std::io::Read) -> std::io::Result<()> { match input.read(&mut [0u8]) { Ok ( 0

Is there any way to create and open a file if it doesn't exist but fail otherwise?

纵然是瞬间 提交于 2020-05-14 14:53:46
问题 It looks like OpenOptions does not support this scenario and an existing file will either be truncated or overwritten. 回答1: As of Rust 1.9.0, there is OpenOptions::create_new which enables you to safely and atomically ensure that you are creating a new file, and that your command will fail otherwise. 回答2: It is possible in C11, or by using low-level OS API functions directly. If you use C11, fopen allows you to open the file in "wx" mode. Otherwise, on Linux, one should pass both O_CREAT and

What is the bitwise NOT operator in Rust?

a 夏天 提交于 2020-05-14 14:37:12
问题 Looking at the list of bitwise operators in the Rust Book, I don't see a NOT operator (like ~ in C). Is there no NOT operator in Rust? 回答1: The ! operator is implemented for many primitive types and it's equivalent to the ~ operator in C. See this example (playground): let x = 0b10101010u8; let y = !x; println!("x: {:0>8b}", x); println!("y: {:0>8b}", y); Outputs: x: 10101010 y: 01010101 See also: How do you set, clear and toggle a single bit in Rust? 来源: https://stackoverflow.com/questions

How to deal with inexact floating point arithmetic results in Rust? [closed]

牧云@^-^@ 提交于 2020-05-14 13:52:08
问题 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 2 years ago . How to deal with floating point arithmetic in Rust? For example: fn main() { let vector = vec![1.01_f64, 1.02, 1.03, 1.01, 1.05]; let difference: Vec<f64> = vector.windows(2).map(|slice| slice[0] - slice[1]).collect(); println!("{:?}", difference); } Returns: [-0

How to import a crate dependency when the library name is different from the package name?

自闭症网瘾萝莉.ら 提交于 2020-05-13 05:39:06
问题 I have a crate that is imported straight off of GitHub, as per Cargo's documentation: [dependencies] libfoo = { git = "ssh://git@github.com/me/libfoo", branch = "dev" } [lib] path = "src/rust/lib.rs" name = "myprj" crate-type = ["cdylib"] Running cargo build works fine here, Cargo fetches libfoo and builds it in the ~/.cargo directory. When I try to use (import) it in lib.rs : extern crate libfoo; //also tried foo Cargo chokes: error[E0463]: can't find crate for `libfoo` --> src/rust/lib.rs:1

Why does my trait need a lifetime parameter?

泄露秘密 提交于 2020-05-13 04:56:40
问题 Being a Rust newbie, I probably somewhat naively started with this: ... pub trait Decode<T> { fn decode_from<R: io::Read + ?Sized>(&mut self, stream: &mut R) -> T; } pub struct MQTTFrame<'a> { pub payload: &'a Vec<u8>, } pub struct MQTTFrameDecoder<'a> { pub payload: &'a mut Vec<u8>, } impl<'a> Decode<MQTTFrame<'a>> for MQTTFrameDecoder<'a> { fn decode_from<R: io::Read + ?Sized>(&mut self, stream: &mut R) -> MQTTFrame<'a> { stream.read(&mut self.payload); MQTTFrame{ payload: self.payload } }