有时候我想从std::io::Reader 读取一个字节.如果我尝试这样做:
use std::io::{self, Read};
fn main() {
let mut byte: u8 = 0;
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte);
}
Run Code Online (Sandbox Code Playgroud)
我得到以下错误(这是明确的,因为byte不是切片):
error[E0308]: mismatched types
--> src/main.rs:6:22
|
6 | io::stdin().read(&mut byte).unwrap();
| ^^^^^^^^^ expected slice, found u8
|
= note: expected type `&mut [u8]`
found type `&mut u8`
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以保持byte简单u8,只需要切片,然后我可以传递给它read()?使这段代码工作的显而易见的方法是使用长度为1的数组:
use std::io::{self, Read};
fn main() {
let mut byte: [u8; 1] = [0];
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte[0]);
}
Run Code Online (Sandbox Code Playgroud)
但是在整个代码中,这有点奇怪的感觉,使用单个u8 …
目前,Rust还没有"特质专业化"功能.据我所知,这意味着对于一种给定类型,特征不能多次实现.然而,我注意到,Borrow特点是实现for T where T: ?Sized这些都是非引用类型有(右?).但它也适用于其他几种类型,例如Vec<T>,它们看起来像专业化.
这怎么样?它是编译器魔术还是我误解了什么特质专业化?
我想通过执行外部程序std::process::Command::spawn.此外,我想知道产生进程失败的原因:是因为给定的程序名不存在/不存在于PATH中还是因为某些不同的错误?
我想要实现的示例代码:
match Command::new("rustc").spawn() {
Ok(_) => println!("Was spawned :)"),
Err(e) => {
if /* ??? */ {
println!("`rustc` was not found! Check your PATH!")
} else {
println!("Some strange error occurred :(");
}
},
}
Run Code Online (Sandbox Code Playgroud)
当我尝试执行不在我的系统上的程序时,我得到:
Error { repr: Os { code: 2, message: "No such file or directory" } }
Run Code Online (Sandbox Code Playgroud)
但我不想依赖于此.有没有办法确定PATH中是否存在程序?
我试图在这个着名的问题中复制这个例子.我的代码看起来像这样:
#![feature(test)]
extern crate rand;
extern crate test;
use test::Bencher;
use rand::{thread_rng, Rng};
type ItemType = u8;
type SumType = u64;
const TEST_SIZE: usize = 32_768;
#[bench]
fn bench_train(b: &mut Bencher) {
let numbers = get_random_vec();
b.iter(|| calc_sum(&numbers));
}
#[bench]
fn bench_train_sort(b: &mut Bencher) {
let mut numbers = get_random_vec();
numbers.sort(); // <-- the magic difference
b.iter(|| calc_sum(&numbers));
}
fn get_random_vec() -> Vec<ItemType> {
thread_rng().gen_iter().take(TEST_SIZE).collect()
}
fn calc_sum(numbers: &Vec<ItemType>) -> SumType {
let mut sum = 0;
for …Run Code Online (Sandbox Code Playgroud) 在Rust 1.14中,Index特征定义如下:
pub trait Index<Idx> where Idx: ?Sized {
type Output: ?Sized;
fn index(&self, index: Idx) -> &Self::Output;
}
Run Code Online (Sandbox Code Playgroud)
这里放宽Sized了Output类型的隐式绑定?Sized.这是有道理的,因为该index()方法返回一个引用Output.因此,可以使用未实现的类型,这是有用的; 例:
impl<T> Index<Range<usize>> for Vec<T> {
type Output = [T]; // unsized!
fn index(&self, index: Range<usize>) -> &[T] { … } // no problem: &[T] is sized!
}
Run Code Online (Sandbox Code Playgroud)
该Idx类型参数的隐式绑定也轻松,可以无胶.但是Idx作为方法参数使用值,并且使用未定义类型作为参数是不可能的AFAIK.为什么Idx允许不合格?
我有以下Rust程序,我希望它会导致编译错误,因为x稍后会重新分配.但它符合并提供输出.为什么?
fn main() {
let (x, y) = (1, 3);
println!("X is {} and Y is {}", x, y);
let x: i32 = 565;
println!("Now X is {}", x);
}
Run Code Online (Sandbox Code Playgroud) 为什么这个指针算术(没有读取或写入这些指针后面的数据)是segfault的原因?
#![allow(dead_code,unused_variables)]
use std::cell::Cell;
struct Bar<T: ?Sized> {
a: Cell<usize>,
value: T,
}
unsafe fn foo<T: ?Sized>(v: &T) {
let fake: &Bar<T> = std::mem::zeroed();
// segfault on this line
// we are not reading or writing uninitialized data behind the reference,
// but only doing pointer arithmetic. We are not reading or writing
// uninitialized vtable, but only copy the vtable pointer.
let fake_val = &fake.value;
}
fn main() {
use std::any::Any;
let some_ref: &Any = &42 as &Any;
unsafe …Run Code Online (Sandbox Code Playgroud) 我有一个特性,我想为所有实现的类型实现它std::ops::Index.这段代码有效(正如我所料):
use std::ops::Index;
use std::fmt::Display;
trait Foo {
fn foo(&self, i: usize) -> &Display;
}
impl<C> Foo for C
where
C: Index<usize>,
C::Output: Display + Sized,
{
fn foo(&self, i: usize) -> &Display {
&self[i]
}
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
但是,一旦我将一个通用参数引入我的特性,我就会遇到奇怪的生命周期错误.这是代码(Playground):
trait Foo<T> {
fn foo(&self, i: T) -> &Display;
}
impl<C, T> Foo<T> for C
where
C: Index<T>,
C::Output: Display + Sized,
{
fn foo(&self, i: T) -> &Display {
&self[i]
}
}
Run Code Online (Sandbox Code Playgroud)
而奇怪的错误(显然这是一个错误,在略有不同的版本中重复三次): …
我想记录我的箱子并在文档中包含一个表格:
//! Demonstrating MarkDown tables.
//!
//! | Foo | Bar | Baz | Qux |
//! | --- | --- | --- | --- |
//! | Hail the turbofish `::<>` | Ferris for president | I can't think of any more "funny" things | oopsie |
//!
Run Code Online (Sandbox Code Playgroud)
渲染cargo doc结果如下:
这就是我要的。但是,您可能已经注意到,源代码行非常长。事实上,长度超过100个字符。与许多 Rust 项目一样,我希望将所有行的长度控制在 100 个字符以内。所以我试图以某种方式打破界限。
所有这些版本:
//! | Foo | Bar | Baz | Qux |
//! | --- | --- | --- | --- |
//! …Run Code Online (Sandbox Code Playgroud) 我有以下 Rust 程序。
fn main() {
let v = vec![100, 32, 57];
for i in v {
println!("{}", i);
}
println!("{:?}", v);
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到:
fn main() {
let v = vec![100, 32, 57];
for i in v {
println!("{}", i);
}
println!("{:?}", v);
}
Run Code Online (Sandbox Code Playgroud)
该错误指出在 处发生了移动for i in v。但我只是使用v由let v = vec![100, 32, 57]. 它不是像 那样的东西let v2 = v; for i in v2 ...,它将值从v移到v2。谁能帮忙解释一下?