rust

Why does re-borrowing only work on de-referenced pointers?

不打扰是莪最后的温柔 提交于 2021-02-10 14:23:28
问题 This question and code are adapted from Why does creating a mutable reference to a dereferenced mutable reference work?. The answers there explained re-borrowing but not the reasons for the conventions around it. The two calls to test below seem equivalent, why does only the first one work? fn main() { let mut string = String::new(); let ref_string = &mut string; // Compiles test(&mut *ref_string); // Doesn't compile test(&mut string); } fn test(s: &mut String) { s.push('t'); } 回答1: You are

Why does re-borrowing only work on de-referenced pointers?

女生的网名这么多〃 提交于 2021-02-10 14:20:40
问题 This question and code are adapted from Why does creating a mutable reference to a dereferenced mutable reference work?. The answers there explained re-borrowing but not the reasons for the conventions around it. The two calls to test below seem equivalent, why does only the first one work? fn main() { let mut string = String::new(); let ref_string = &mut string; // Compiles test(&mut *ref_string); // Doesn't compile test(&mut string); } fn test(s: &mut String) { s.push('t'); } 回答1: You are

How do I conditionally order by a column based on a dynamic parameter with Diesel?

那年仲夏 提交于 2021-02-10 14:18:12
问题 I'm trying to specify different columns for order_by depending on an external parameter. This works, but is ugly: #[macro_use] extern crate diesel; use crate::diesel::prelude::*; use diesel::pg::PgConnection; mod schema { table! { items (id) { id -> Int4, name -> Text, } } } #[derive(Queryable, Debug)] pub struct Item { pub id: i32, pub name: String, } fn load_items(conn: PgConnection, sort_prop: String, sort_dir: String) -> Vec<Item> { use schema::items::dsl::*; let mut query = items.into

Lifetime parameter for `Self` in trait signature

和自甴很熟 提交于 2021-02-10 13:07:36
问题 Consider this simple protocol implementation: #[derive(PartialEq, Debug)] enum Req<'a> { InputData(&'a [u8]), Stop, } impl<'a> Req<'a> { fn decode(packet: &'a [u8]) -> Result<Req<'a>, String> { match packet.first() { Some(&0x01) => Ok(Req::InputData(&packet[1..])), Some(&0x02) => Ok(Req::Stop), _ => Err(format!("invalid request: {:?}", packet)), } } } #[derive(PartialEq, Debug)] enum Rep<'a> { OutputData(&'a [u8]), StopAck, } impl<'a> Rep<'a> { fn decode(packet: &'a [u8]) -> Result<Rep<'a>,

Lifetime parameter for `Self` in trait signature

与世无争的帅哥 提交于 2021-02-10 13:06:52
问题 Consider this simple protocol implementation: #[derive(PartialEq, Debug)] enum Req<'a> { InputData(&'a [u8]), Stop, } impl<'a> Req<'a> { fn decode(packet: &'a [u8]) -> Result<Req<'a>, String> { match packet.first() { Some(&0x01) => Ok(Req::InputData(&packet[1..])), Some(&0x02) => Ok(Req::Stop), _ => Err(format!("invalid request: {:?}", packet)), } } } #[derive(PartialEq, Debug)] enum Rep<'a> { OutputData(&'a [u8]), StopAck, } impl<'a> Rep<'a> { fn decode(packet: &'a [u8]) -> Result<Rep<'a>,

Difference in mutability between reference and box

拟墨画扇 提交于 2021-02-10 12:33:51
问题 I'm trying to understand Rust pointer types and their relation to mutability. Specifically, the ways of declaring a variable which holds the pointer and is itself mutable -- i.e. can be pointed to some other memory, and declaring that the data itself is mutable -- i.e. can be changed through the value of the pointer variable. This is how I understand plain references work: let mut a = &5; // a is a mutable pointer to immutable data let b = &mut 5; // b is an immutable pointer to mutable data

Does move on a closure copy the reference “pointer” or the actual object referenced?

拥有回忆 提交于 2021-02-10 07:41:12
问题 This code does not compile without adding move to the closure. It produces the error: error[E0373]: closure may outlive the current function, but it borrows `foo`, which is owned by the current function --> src/main.rs:26:18 | 26 | do_something(|| { | ^^ may outlive borrowed value `foo` 27 | foo.bar += 1; | --- `foo` is borrowed here | note: function requires argument type to outlive `'static` --> src/main.rs:26:5 | 26 | / do_something(|| { 27 | | foo.bar += 1; 28 | | println!("{}", foo.bar);

Type must be known in this context when using Iterator::sum [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-02-10 06:19:16
问题 This question already has an answer here : Type must be known in this context when using Iterator::collect (1 answer) Closed 3 years ago . I am trying to implement a trait that models the euclidean distance between 2 points in an n-dim space. The points are represented as Vec<u32> . pub trait Point { fn euclidean_to(&self, other: Vec<u32>) -> f64; } impl Point for Vec<u32> { fn euclidean_to(&self, other: Vec<u32>) -> f64 { (self.iter() .zip(other.iter()) .map(|(xa, xb): (&u32, &u32)| (xa - xb

How to pass Iterator<String> as Iterator<&str>?

自古美人都是妖i 提交于 2021-02-10 05:23:03
问题 fn my_print<'a>(args: impl Iterator<Item=&'a str>) { for arg in args { println!("=> {}", arg); } } fn main() { let vec = vec!["one".to_string(), "two".to_string()]; my_print(vec.into_iter()); // how to pass vec here? } How do I convert Iterator<T> to Iterator<U> and pass it to another function? 回答1: An even better way would be to write the function in a way such as it doesn't actually care: fn my_print<T: AsRef<str>>(args: impl Iterator<Item = T>) { for arg in args { println!("=> {}", arg.as

How to pass Iterator<String> as Iterator<&str>?

帅比萌擦擦* 提交于 2021-02-10 05:22:48
问题 fn my_print<'a>(args: impl Iterator<Item=&'a str>) { for arg in args { println!("=> {}", arg); } } fn main() { let vec = vec!["one".to_string(), "two".to_string()]; my_print(vec.into_iter()); // how to pass vec here? } How do I convert Iterator<T> to Iterator<U> and pass it to another function? 回答1: An even better way would be to write the function in a way such as it doesn't actually care: fn my_print<T: AsRef<str>>(args: impl Iterator<Item = T>) { for arg in args { println!("=> {}", arg.as