rust

How to build json arrays or objects dynamically with serde_json?

我的梦境 提交于 2021-01-29 12:30:51
问题 I need to build a json object at runtime. For now, just a simple {"key": "stringvalue"} object. But each key/val pair must be added in a loop. This seems really simple/basic, but I didn't find any good examples or docs on it. I did finally manage to make something work, but it seems too convoluted to be the right way. Can anyone post a working example? 回答1: You can do this with serde_json::Value : use serde_json::{Map, Value}; let mut map = Map::new(); // assuming keys_vals is a Vec<(String,

Borrowed value does not live long enough with a Tokio future

[亡魂溺海] 提交于 2021-01-29 12:13:01
问题 I'm trying to write a simple HTTP server using Rust and tokio. Everything works fine until I want to send the response. The code is the following: use std::fs; use std::sync::Arc; use tokio::net::TcpListener; // 0.1.15 use tokio::prelude::*; fn main() { let addr = "0.0.0.0:8080".parse().unwrap(); let listener = TcpListener::bind(&addr).expect("unable to bind TCP listener"); let incoming = listener.incoming(); let server = incoming .map_err(|e| eprintln!("accept failed = {:?}", e)) .for_each(

How do I convert a static global variable generated by Bindgen into a global const?

☆樱花仙子☆ 提交于 2021-01-29 11:54:40
问题 Bindgen generates this from a static const C-style global structure: pub struct rmw_qos_profile_t { pub depth: usize, pub deadline: rmw_time_t, // ... } extern "C" { #[link_name = "\u{1}rmw_qos_profile_sensor_data"] pub static rmw_qos_profile_sensor_data: rmw_qos_profile_t; } I would like to safely bind it to a global const in Rust. My best attempt so far is impl From<rmw_qos_profile_t> for QoSProfile { fn from(qos_profile: rmw_qos_profile_t) -> Self { QoSProfile { depth: qos_profile.depth,

How can I implement a trait in scope for an enum of existing types for which the trait is implemented?

人走茶凉 提交于 2021-01-29 11:10:03
问题 How can I implement a trait in scope for an enum of existing types for which the trait is implemented? I have this: extern crate pnet; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::ipv6::Ipv6Packet; enum EthernetType { IPv4, ARP, VLAN, IPv6, Unknown(u16), } enum IPPacket<'a> { IPv4(Ipv4Packet<'a>), IPv6(Ipv6Packet<'a>), } fn ip_decode(pkt: &[u8]) -> IPPacket { let version = (pkt[0] & 0xf0) >> 4; if version == 4 { IPPacket::IPv4(Ipv4Packet::new(&pkt).unwrap()) } else { IPPacket::IPv6

How to push a value to a Vec and append it to a String at the same time?

我的梦境 提交于 2021-01-29 11:09:10
问题 I want to write a program that sets the shell for the system's nslookup command line program: fn main() { let mut v: Vec<String> = Vec::new(); let mut newstr = String::from("nslookup"); for arg in std::env::args() { v.push(arg); newstr.push_str(&format!(" {}", arg)); } println!("{:?}", v); println!("{}", newstr); } error[E0382]: borrow of moved value: `arg` --> src/main.rs:6:41 | 5 | v.push(arg); | --- value moved here 6 | newstr.push_str(&format!(" {}", arg)); | ^^^ value borrowed here after

Create closure returning iterator on string

青春壹個敷衍的年華 提交于 2021-01-29 10:57:35
问题 I want to write a closure that takes an object and returns an iterator from it. The idea is to store the closure in a structure and apply as needed: fn main() { let iter_wrap = |x: &String| Box::new(x.chars()); let test = String::from("test"); for x in iter_wrap(&test) { println!("{}", x); } } This causes the error: error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements --> src/main.rs:2:45 | 2 | let iter_wrap = |x: &String|

Errors in overwriting slice reference with sub-slice reference

走远了吗. 提交于 2021-01-29 10:46:12
问题 I'm trying to nail down ownership rules. I want to: start with a mutable reference to a slice make some edits to its contents reduce the slice reference to a reference of a sub-slice and repeat Below is my attempt: pub fn example() { // Make a mutable slice let mut v = [0, 1, 2, 3]; // Make a mutable reference to said slice let mut v_ref = &mut v[..]; while v_ref.len() > 1 { // Involves some edits -> need mut v_ref.swap(0, v_ref.len() - 1); // Try to reduce slice to sub-slice (some

Specifying static lifetime of value in `main` so callback can borrow [duplicate]

与世无争的帅哥 提交于 2021-01-29 10:24:37
问题 This question already has answers here : How do I call a function that requires a 'static lifetime with a variable created in main? (2 answers) How do I create a global, mutable singleton? (3 answers) Closed 2 years ago . I have a variable that I am using to keep track of state which is updated by a handler closure. Something like the following: fn main() { let val = 1; add_handler(|| val += 1); println!("{}", val); } The add_handler function is declared in another library and has the type fn

Update drawing function of a DrawingArea

杀马特。学长 韩版系。学妹 提交于 2021-01-29 09:23:11
问题 I want to update a cairo drawing inside a DrawingArea. I tried to achieve this by calling DrawingArea::connect_draw(...) with a new function as the parameter. My issue is that it does not replace the original drawing function, but calls both when showing the window. Here is an example extern crate cairo; extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; fn main() { let application = gtk::Application::new(Some("com.example"), Default::default()) .expect(

How to change order of letters in every word beside first and last letter in sentence in RUST? [duplicate]

让人想犯罪 __ 提交于 2021-01-29 08:44:14
问题 This question already has an answer here : How to shuffle a vector except for the first and last elements without using third party libraries? (1 answer) Closed 9 months ago . I need to change order of letter in every word of sentence besides first and last letter (example:"According, researcher" => "Accroidng, rseaecrehr" or "University, it doesn't matter" => "Uinevsrtiy, it deosn't mtaetr"). I have constant of separators to split my string on words. Semicolon, comma or other separator must