这段代码:
use std::collections::HashMap;
struct MyNode;
struct MyEdge;
struct Graph<N, E> {
h: HashMap<N, Vec<E>>,
}
type MyGraph = Graph<MyNode, MyEdge>;
fn main() {
let x: MyGraph::N;//XXX
println!("Results:")
}
Run Code Online (Sandbox Code Playgroud)
无法编译错误:
error[E0223]: ambiguous associated type
--> /home/xxx/.emacs.d/rust-playground/at-2017-07-26-164119/snippet.rs:21:12
|
21 | let x: MyGraph::N;
| ^^^^^^^^^^ ambiguous associated type
|
= note: specify the type using the syntax `<Graph<MyNode, MyEdge> as Trait>::N`
Run Code Online (Sandbox Code Playgroud)
有没有办法从中获取N类型Graph<MyNode, MyEdge>?
我创建了一个type =不复制节点类型定义的别名(),所以在XXX我可以写的标记点上它会很棒let x: MyNode但是let x: expression with MyGraph …
在这段代码中:
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]));
}
Run Code Online (Sandbox Code Playgroud)
该函数unpack_u32只接受长度为 4 的切片。有没有办法assert_eq用编译时检查替换运行时检查?
是否有可能向编译器解释v变量是否擅长标记为1不使用不安全的行或可能调用的代码panic!?
#[derive(PartialEq, Debug)]
enum Enum {
V1,
V2,
V3,
}
fn main() {
let e = Enum::V1;
let mut v: i32;
if e == Enum::V1 || e == Enum::V2 {
v = 17; //some complex, costy expression
}
match e {
Enum::V1 | Enum::V2 => {
println!("Results: {}", v); //1
}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器报告:
error[E0381]: use of possibly uninitialized variable: `v`
--> src/main.rs:18:37
|
18 | println!("Results: {}", v); //1
| …Run Code Online (Sandbox Code Playgroud) 我想调用为type实现的方法&[i32]。我可以通过标记为1的行中所示的类型别名来做到这一点,但是是否可以不必每次都引入类型别名呢?
trait Foo<T> {
fn say_hi(x: T);
}
impl<'a> Foo<i32> for &'a [i32] {
fn say_hi(x: i32) {}
}
type Array<'a> = &'a [i32];
fn main() {
let arr = [1, 2, 3];
Array::say_hi(1);//line 1
&[i32]::say_hi(1);//line 2
}
Run Code Online (Sandbox Code Playgroud)
标记为2的行会产生错误消息:
trait Foo<T> {
fn say_hi(x: T);
}
impl<'a> Foo<i32> for &'a [i32] {
fn say_hi(x: i32) {}
}
type Array<'a> = &'a [i32];
fn main() {
let arr = [1, 2, 3];
Array::say_hi(1);//line 1
&[i32]::say_hi(1);//line …Run Code Online (Sandbox Code Playgroud) 我想PathBuf在我的结构内部保存一个:
use std::path::{Path, PathBuf};
struct Foo {
p: PathBuf,
}
impl Foo {
fn new(p: PathBuf) -> Foo {
Foo { p }
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西适用于Foo::new(Path::new("a").join("b")),但我也想支持Foo::new(Path::new("a")):
fn main() {
Foo::new(Path::new("a").join("b"));
// Foo::new(Path::new("a"));
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?是否可以用一种方法实现,还是应该使用两种方法?我知道P: AsRef<Path>,但看起来它需要额外的副本
let p: PathBuf = Path::new("a").join("b");
let foo = Foo::new(p);
Run Code Online (Sandbox Code Playgroud)
所以它不适合我。
我想为我的板条箱创建一个C FFI API,但尚不清楚强制转换指针的安全性。伪代码:
#[no_mangle]
extern "C" fn f(...) -> *mut c_void {
let t: Box<T> = ...;
let p = Box::into_raw(t);
p as *mut c_void
}
Run Code Online (Sandbox Code Playgroud)
这可以按预期工作,但它的安全性如何?在C或C ++中,有一个特殊的void *指针,并且C ++标准声明可以强制转换为它。潜在地,sizeof(void *)可以是不相等的sizeof(T *),但有一个保证sizeof(void *)> = sizeof(T *)。
那Rust呢?是否有关于std::mem::size_of指针的保证或指针之间的安全转换?还是所有指针的实现大小相等,等于usize?
“通用”是指您可以转换X *而不会丢失任何东西。我不在乎类型信息;我关心的是指向不同事物的指针的大小不同,例如16位天中的near/ far指针。
4.10说
将“ pointer to cv T”转换为“ pointer to cv void”的结果指向类型为T的对象所在的存储位置的起点,
,这是不可能的sizeof(void *) < sizeof(T *),因为那样就不可能拥有存储位置的真实地址。
我为这样的代码尝试了 gcc (9.2.1) 和 clang (9.0.1) 的最新版本:
//pure.cpp
int square (int x) __attribute__ ((pure));
int square (int x)
{
return x * x;
}
//test.cpp
#include <stdio.h>
int square (int x) __attribute__ ((pure));
int main(int argc, char *argv[])
{
const int same = argc;
printf("result: %d\n", square(same));
printf("result2: %d\n", square(same));
}
Run Code Online (Sandbox Code Playgroud)
并像这样编译它:
g++ -ggdb -Ofast -c test.cpp
g++ -ggdb -Ofast -c pure.cpp
g++ -ggdb -Ofast -o test test.o pure.o
Run Code Online (Sandbox Code Playgroud)
结果我看到:
1043: e8 58 01 00 00 callq 11a0 <_Z6squarei>
1048: …Run Code Online (Sandbox Code Playgroud) 当且仅当a和b不是时,我想执行操作None.我不想创建复杂结构的副本,这就是为什么struct X不实现Clone.
use std::sync::{Arc, Mutex};
use std::cell::RefCell;
#[derive(Debug)]
struct X {
d: u32,
}
struct Foo {
a: Option<X>,
b: Option<u32>,
c: u32,
}
fn main() {
let smart_ptr = Arc::new(Mutex::new(RefCell::new(Foo {
a: Some(X { d: 1 }),
b: Some(2),
c: 3,
})));
{
let lock = smart_ptr.lock().unwrap();
let foo = lock.borrow();
if let (Some(ref a), Some(b)) = (foo.a, foo.b) {
println!("a: {:?}, b: {}", a, b);
}
}
} …Run Code Online (Sandbox Code Playgroud) 我想检查字符串是否以字符串开头"|<any char><any char>TD".我已经验证字符串只包含0..9,az,AZ,空格,','和'*'.
包括用于此类任务的正则表达式包是太多开销,而我认为我需要类似的东西
fn get_slice(s: &str, range: Range<usize>) -> Option<&str> {
unimplemented!();
}
Run Code Online (Sandbox Code Playgroud)
它可以像:
let is_good_string: bool =
get_slice(s, (0..5)).map_or(false, |v: &str| &v[0..1] == "|" && &v[3..5] == "TD");
Run Code Online (Sandbox Code Playgroud)
标准库中有没有类似于我的功能get_slice?是否有可能以其他方式借助标准库函数来解决我的任务?
我有这个简单的代码:
#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
struct NodeIndex(u32);
fn main() {
let i = NodeIndex(5323);
let from = NodeIndex(21030);
let to = NodeIndex(21031);
println!("from == i => {}, to == i => {}", from == i, to == i);
match i {
from => println!("1"),
to => println!("2"),
_ => println!("other"),
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
from == i => false, to == i => false
1
Run Code Online (Sandbox Code Playgroud)
所以i != from,i != to但是match打电话from …
例如:
use futures::future::Future;
fn main() {
let (stop_tokio, time_to_stop) = tokio::sync::oneshot::channel::<()>();
let handler = std::thread::spawn(|| {
tokio::run(
time_to_stop, // .map_err(|_| ())
);
});
handler.join().expect("join failed");
}
Run Code Online (Sandbox Code Playgroud)
编译器显示错误:
use futures::future::Future;
fn main() {
let (stop_tokio, time_to_stop) = tokio::sync::oneshot::channel::<()>();
let handler = std::thread::spawn(|| {
tokio::run(
time_to_stop, // .map_err(|_| ())
);
});
handler.join().expect("join failed");
}
Run Code Online (Sandbox Code Playgroud)
该代码要求使用(),RecvError但改为,但是编译器打印相反的代码。
这是编译器中的错误,还是我错过了什么?