我正在尝试匹配结构的通用字段的数据类型并做出相应的反应.我的总体想法是这样的(代码不编译):
struct Foo<T> {
bar: T,
}
fn main() {
let x = Foo::<String> {
bar: "world".to_string(),
};
match x.bar {
String => println!("It's a string!"),
u32 => println!("It's a u32!"),
_ => println!("Something else"),
};
println!("end of program!");
}
Run Code Online (Sandbox Code Playgroud)
来自的错误消息x:
warning: unreachable pattern
--> src/main.rs:12:9
|
11 | String => println!("It's a string!"),
| ------ matches any value
12 | u32 => println!("It's a u32!"),
| ^^^ unreachable pattern
|
= note: `#[warn(unreachable_patterns)]` on by default
warning: …Run Code Online (Sandbox Code Playgroud) 我正在尝试进行结构序列化,其中字节最终将被发送到管道,重建并在它们上调用方法.
我创建了一个特征,这些结构将适当地实现,我使用serde和serde-cbor进行序列化:
extern crate serde_cbor;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use serde_cbor::ser::*;
use serde_cbor::de::*;
trait Contract {
fn do_something(&self);
}
#[derive(Debug, Serialize, Deserialize)]
struct Foo {
x: u32,
y: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Bar {
data: Vec<Foo>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Baz {
data: Vec<Foo>,
tag: String,
}
impl Contract for Bar {
fn do_something(&self) {
println!("I'm a Bar and this is my data {:?}", self.data);
}
}
impl Contract for Baz {
fn do_something(&self) …Run Code Online (Sandbox Code Playgroud) 我有一个结构,包含一个像这样的特征对象成员:
trait Contract {}
#[derive(Debug)]
struct Foo {
x: Box<Contract>,
}
Run Code Online (Sandbox Code Playgroud)
我想要派生这个结构Debug,但编译器不喜欢它:
error[E0277]: `Contract + 'static` doesn't implement `std::fmt::Debug`
--> src/main.rs:5:5
|
5 | x: Box<Contract>,
| ^^^^^^^^^^^^^^^^ `Contract + 'static` cannot be formatted using `:?`; add `#[derive(Debug)]` or manually implement `std::fmt::Debug`
|
= help: the trait `std::fmt::Debug` is not implemented for `Contract + 'static`
= note: required because of the requirements on the impl of `std::fmt::Debug` for `std::boxed::Box<Contract + 'static>`
= note: required because of the requirements …Run Code Online (Sandbox Code Playgroud) 正如问题所述,我该如何实现这一目标?
如果我有这样的代码:
let a = "29";
for c in a.chars() {
println!("{}", c as u32);
}
Run Code Online (Sandbox Code Playgroud)
我得到的是2和9的unicode代码点:
我想要的是将这些字符解析为实际数字.
我正在尝试实现Serialize一个包含结构变体的枚举。serde.rs 文档指出以下内容:
enum E {
// Use three-step process:
// 1. serialize_struct_variant
// 2. serialize_field
// 3. end
Color { r: u8, g: u8, b: u8 },
// Use three-step process:
// 1. serialize_tuple_variant
// 2. serialize_field
// 3. end
Point2D(f64, f64),
// Use serialize_newtype_variant.
Inches(u64),
// Use serialize_unit_variant.
Instance,
}
Run Code Online (Sandbox Code Playgroud)
考虑到这一点,我开始实施:
use serde::ser::{Serialize, SerializeStructVariant, Serializer};
use serde_derive::Deserialize;
#[derive(Deserialize)]
enum Variants {
VariantA,
VariantB { k: u32, p: f64 },
}
impl Serialize for Variants { …Run Code Online (Sandbox Code Playgroud) 我正在尝试读取 TOML 文件以创建一个结构,该结构包含具有关联值的枚举向量。这是示例代码:
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate toml;
use std::fs::File;
use std::io::Read;
#[derive(Debug, Deserialize, PartialEq)]
struct Actor {
name: String,
actions: Vec<Actions>,
}
#[derive(Debug, Deserialize, PartialEq)]
enum Actions {
Wait(usize),
Move { x: usize, y: usize },
}
fn main() {
let input_file = "./sample_actor.toml";
let mut file = File::open(input_file).unwrap();
let mut file_content = String::new();
let _bytes_read = file.read_to_string(&mut file_content).unwrap();
let actor: Actor = toml::from_str(&file_content).unwrap();
println!("Read actor {:?}", actor);
}
Run Code Online (Sandbox Code Playgroud)
Cargo.toml
[dependencies]
serde_derive = "1.0.10" …Run Code Online (Sandbox Code Playgroud) 我正在编写一个应用程序,该应用程序使用 slog 在其执行期间记录多项内容。因此,我广泛利用的info!,error!,warn!和debug!宏。
然而,正如预期的那样,这些debug!调用是为了帮助我调试应用程序,我不希望这些调用在实际使用应用程序时污染日志。
我一直试图编译它们但没有成功。这是我正在使用的线路:RUSTFLAGS="$RUSTFLAGS -C debug-assertions" cargo build --release
编译进行得很顺利,但在执行时我看到了所有的调试调用。
以下是我的问题的一个工作示例:
货物.toml:
[dependencies]
slog = { version = "1.5", features = ["max_level_trace", "release_max_level_warn"] }
slog-stream = "1.2.0"
slog-term = "1.5.0"
slog-json = "1.2.1"
slog-stdlog = "1.1.0"
log = "0.3.7"
Run Code Online (Sandbox Code Playgroud)
主.rs:
#[macro_use]
extern crate slog;
extern crate slog_stream;
extern crate slog_term;
extern crate slog_json;
extern crate slog_stdlog;
#[macro_use]
extern crate log;
use std::path::Path;
use std::fs::OpenOptions;
use slog::DrainExt;
fn init_logger(work_dir …Run Code Online (Sandbox Code Playgroud) 我在 Postgres 数据库中有以下架构:
Table A {
ID
Name
}
Table B {
ID FOREIGN KEY (A.ID)
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在 Diesel 中编写以下查询:
DELETE FROM B
WHERE B.ID in (SELECT ID from A WHERE A.Name = $VAR)
Run Code Online (Sandbox Code Playgroud)
$VAR 是我的应用程序传递的变量。
我第一次尝试写这篇文章如下:
fn deleteB(conn: &PgConnection, n: &str) {
use schema::A::dsl::*;
use schema::A;
use schema::B;
let res = A::table
.filter(Name.eq(n))
.select(ID);
.load(conn)
.unwrap();
assert!(res.len() < 2);
let b_id: i32 = *res.iter().nth(1).unwrap_or(&0);
let _rows = diesel::delete(
B::table
.filter(ID.eq(n_id))
)
.execute(conn)
.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
这编译但它不起作用:SELECTID的语句总是返回 0。它不匹配 A …
我正在尝试生成一组给定的线程,并且每个线程执行一个长时间运行的操作.我将一个结构传递给每个工作线程作为给定线程的内部状态.所述结构的集合保存在向量中,Master结构的一部分.
编译器拒绝我将结构的内部成员传递给Arc::new():
use std::thread;
use std::sync::Arc;
struct Worker {
name: String,
}
struct Master {
workers: Vec<Worker>,
}
impl Worker {
fn start(&self) {
println!("My name is {} and I'm working!", self.name);
thread::sleep_ms(100_000);
}
}
impl Master {
pub fn run_test(&mut self) {
for i in 0..10 {
self.workers.push(Worker {
name: String::new() + "Worker" + &i.to_string()
});
}
let mut data = Arc::new(self.workers);
for i in 0..10 {
let local_data = data.clone();
thread::spawn(move || {
local_data[i].start(); …Run Code Online (Sandbox Code Playgroud)