我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)
有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)
有时,我甚至没有参考该值,我得到同样的错误:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?
由于Rust比较新,我看到了很多阅读和编写文件的方法.许多人为他们的博客提出了非常混乱的片段,我发现的99%的例子(即使在Stack Overflow上)来自不稳定的构建,不再有效.现在Rust是稳定的,什么是简单,可读,非恐慌的读取或写入文件片段?
这是我最接近阅读文本文件的东西,但它仍然没有编译,即使我很确定我已经包含了我应该拥有的一切.这是基于我在所有地方的Google+上发现的一个片段,我唯一改变的是旧BufferedReader的现在只是BufReader:
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
fn main() {
let path = Path::new("./textfile");
let mut file = BufReader::new(File::open(&path));
for line in file.lines() {
println!("{}", line);
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
error: the trait bound `std::result::Result<std::fs::File, std::io::Error>: std::io::Read` is not satisfied [--explain E0277]
--> src/main.rs:7:20
|>
7 |> let mut file = BufReader::new(File::open(&path));
|> ^^^^^^^^^^^^^^
note: required by `std::io::BufReader::new`
error: no method named `lines` found for type `std::io::BufReader<std::result::Result<std::fs::File, std::io::Error>>` in the current scope
--> src/main.rs:8:22
|> …Run Code Online (Sandbox Code Playgroud) 以下Rust代码编译并运行没有任何问题.
fn main() {
let text = "abc";
println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)
在那之后,我尝试了类似的东西....但它没有编译
fn main() {
let text = "word1 word2 word3";
println!("{}", to_words(text).take(2).count());
}
fn to_words(text: &str) -> &Iterator<Item = &str> {
&(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)
主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:
error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
--> src/main.rs:3:43
|
3 | println!("{}", to_words(text).take(2).count());
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
`std::iter::Iterator<Item=&str> : std::marker::Sized`
`std::iter::Take<std::iter::Iterator<Item=&str>> …Run Code Online (Sandbox Code Playgroud) 有几个问题似乎与我遇到的问题有关.例如,请看这里和这里.基本上我正在尝试String在本地函数中构建一个函数,但是然后将其作为一个函数返回&str.切片不起作用,因为寿命太短.我无法str直接在函数中使用,因为我需要动态构建它.但是,我也不想返回a,String因为一旦它构建完成,它进入的对象的性质就是静态的.有没有办法让我的蛋糕也吃?
这是一个最小的非编译复制:
fn return_str<'a>() -> &'a str {
let mut string = "".to_string();
for i in 0..10 {
string.push_str("ACTG");
}
&string[..]
}
Run Code Online (Sandbox Code Playgroud) 我只花了一个星期阅读Rust Book,现在我正在开发我的第一个程序,它将文件路径返回到系统壁纸:
pub fn get_wallpaper() -> &str {
let output = Command::new("gsettings");
// irrelevant code
if let Ok(message) = String::from_utf8(output.stdout) {
return message;
} else {
return "";
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误expected lifetime parameter on &str,我知道Rust想要一个输入&str,它将作为输出返回,因为&str我在函数内部创建的任何内容都将在函数结束后立即清理.
我知道我可以通过返回一个String而不是一个来回避这个问题&str,并且对类似问题的许多答案已经说了很多.但我似乎也可以这样做:
fn main() {
println!("message: {}", hello_string(""));
}
fn hello_string(x: &str) -> &str {
return "hello world";
}
Run Code Online (Sandbox Code Playgroud)
得到&str我的功能.有人可以向我解释为什么这很糟糕,为什么我不应该这样做?或者也许它在某些情况下并不坏并且没问题?
为什么这段代码会编译?
fn get_iter() -> impl Iterator<Item = i32> {
[1, 2, 3].iter().map(|&i| i)
}
fn main() {
let _it = get_iter();
}
Run Code Online (Sandbox Code Playgroud)
[1, 2, 3]是一个局部变量并iter()借用它.此代码不应编译,因为返回的值包含对局部变量的引用.
在下面的代码中,如何返回引用floor而不是新对象?是否可以让函数返回借用的引用或拥有的值?
extern crate num; // 0.2.0
use num::bigint::BigInt;
fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> BigInt {
let c: BigInt = a - b;
if c.ge(floor) {
c
} else {
floor.clone()
}
}
Run Code Online (Sandbox Code Playgroud) 我试图使用以下代码返回向量的值.我收到错误消息.
fn merge<'a>(left: &'a [i32], right: &'a [i32]) -> [i32] {
let mut merged: Vec<i32> = Vec::new();
// push elements to merged
*merged
}
Run Code Online (Sandbox Code Playgroud)
test.rs:19:52:19:57错误:
core::marker::Sized类型[i32]test.rs:19 fn merge <'a>(左:&'a [i32],右:&'a [i32] ) - > [i32] {
我不能为我的生活找到我如何解决这个问题
作为学习Rust的练习,我决定实现一个Bit Vector库,其灵感来自std::vec::Vec于提供哪些方法.
我有以下代码:
extern crate num;
use std::cmp::Eq;
use std::ops::{BitAnd,BitOrAssign,Index,Shl};
use num::{One,Zero,Unsigned,NumCast};
pub trait BitStorage: Sized +
BitAnd<Self, Output = Self> +
BitOrAssign<Self> +
Shl<Self, Output = Self> +
Eq + Zero + One + Unsigned + NumCast + Copy {}
impl<S> BitStorage for S where S: Sized +
BitAnd<S, Output = S> +
BitOrAssign<S> +
Shl<S, Output = S> +
Eq + Zero + One + Unsigned + NumCast + Copy {}
pub struct BitVector<S: BitStorage> { …Run Code Online (Sandbox Code Playgroud) 使用不同的模式运行new_foo1并new_foo2返回相同的特征Foo。new_foo1除了更冗长之外,我没有看到它们之间有任何功能差异。两者之间有优选的方式吗?这两种模式有什么微妙的影响吗?
trait Foo {
fn bar(&self);
}
struct FooIm {}
impl Foo for FooIm {
fn bar(&self) {
println!("bar from FooIm")
}
}
fn new_foo1<'a>() -> &'a (dyn Foo + 'a) {
&FooIm {}
}
fn new_foo2() -> Box<dyn Foo> {
let f = FooIm {};
Box::new(f)
}
fn main() {
let f1 = new_foo1();
let f2 = new_foo2();
f1.bar();
f2.bar();
}
Run Code Online (Sandbox Code Playgroud)