我有
fn plus_one(x: &i32) -> i32 {
x + 1
}
fn plus_one_star(x: &i32) -> i32 {
*x + 1
}
fn plus_one_mut(x: &mut i32) -> i32 {
x + 1
}
fn plus_one_mut_star(x: &mut i32) -> i32 {
*x + 1
}
fn main() {
let a: i32 = 5;
let mut b: i32 = 5;
println!("{:?}", plus_one(&a));
println!("{:?}", plus_one_star(&a));
println!("{:?}", plus_one_mut(&mut b));
println!("{:?}", plus_one_mut_star(&mut b));
// I expect all to print '6' as I never actually mutate b …Run Code Online (Sandbox Code Playgroud) 第一个Rust程序将无法编译,因为b它在引用之前被删除r,这是有道理的:
fn main() {
let a = "a";
let v;
{
let b = "b";
v = &b;
}
println!("{}", v);
}
Run Code Online (Sandbox Code Playgroud)
在第二个Rust程序中,b通过函数检索引用,突然之间没有问题:
fn getRef(b: &str) -> &str {
b
}
fn main() {
let a = "a";
let v;
{
let b = "b";
v = getRef(&b);
}
println!("{}", v);
}
Run Code Online (Sandbox Code Playgroud)
问题是,v仍然是一个参考b,并且b超出范围println!().
为什么这两个不同?
在对文档Arc<T>说:
Arc<T>自动解引用T(通过Deref特征),因此你可以调用T类型值的方法Arc<T>.
但有没有办法允许匹配Option-al类型?
这是一个简单的例子:
use std::sync::Arc;
fn main() {
let foo: Arc<Option<String>> = Arc::new(Some("hello".to_string()));
if foo.is_some() {
println!("{}", foo.unwrap());
}
match foo {
Some(hello) => {
println!("{}", hello);
}
None => {}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器错误是:
error[E0308]: mismatched types
--> src/main.rs:11:9
|
11 | Some(hello) => {
| ^^^^^^^^^^^ expected struct `std::sync::Arc`, found enum `std::option::Option`
|
= note: expected type `std::sync::Arc<std::option::Option<std::string::String>>`
found type `std::option::Option<_>`
error[E0308]: mismatched types …Run Code Online (Sandbox Code Playgroud) 我刚刚确认了Vec::contains工作原理。我在下面写了代码,看起来工作正常。
但我不知道它为什么有效,因为它比较&String类型。这是否意味着即使没有取消引用字符串比较也有效?
struct NewStruct {
string_vec: Vec<Option<String>>,
}
fn main() {
let mut mys = NewStruct {
string_vec: Vec::<Option<String>>::new(),
};
mys.string_vec.push(Some("new array".to_string()));
let ref_st = mys.string_vec.iter().filter(|o|o.is_some()).map(|o|o.as_ref().unwrap()).collect::<Vec<&String>>();
println!("result:{:?}", ref_st.contains(&&("some string".to_string())));
println!("result:{:?}", ref_st.contains(&&("new array".to_string())));
println!("Hello, world!");
f64::from(1234_u64 as i32);
}
Run Code Online (Sandbox Code Playgroud) 我有一段代码如下:
fn stream_it(&self) -> Box<dyn Stream<Item=()>> {
Box::new(self.some_field)
}
fn consume_it(&self) {
let a = self.stream_it().map(|i| i);
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误:
fn stream_it(&self) -> Box<dyn Stream<Item=()>> {
Box::new(self.some_field)
}
fn consume_it(&self) {
let a = self.stream_it().map(|i| i);
}
Run Code Online (Sandbox Code Playgroud)
我知道这个Sized要求是必要的,但我不知道如何满足它。甚至可以映射单元流吗?
我是 Rust 的新学习者,我发现*运算符可以通过Deref特征重载。该std::string::String类型已Deref实现特征,该特征返回&str类型。但是,当我进行以下测试时,编译器告诉我 is 的类型s2,并显示错误消息“编译时无法知道str类型值的大小”。str所以代码无法编译。但问题是为什么s2呢str?它不应该是同一类型吗s1?
let owned = "test".to_string(); // owned type is String
let s1 = owned.deref(); // s1 type is &str
let s2 = *owned; // s2 type is str
Run Code Online (Sandbox Code Playgroud) 当我尝试编译此代码(playground)时:
fn main() {
let iter = "abc123".chars().filter(&|&c: &char| c.is_digit(10));
match iter.clone().take(3).count() {
3 => println!("{}", iter.collect::<String>()),
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error: borrowed value does not live long enough
--> test.rs:2:41
|
2 | let iter = "abc123".chars().filter(&|c: &char| c.is_digit(10));
| ^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value only lives until here
| |
| temporary value created here
...
7 | }
| - temporary value needs to live until here
|
= note: consider using a `let` …Run Code Online (Sandbox Code Playgroud) 我很困惑为什么该函数get适用于Vec<T>和&Vec<T>。我知道在某种意义上&Vec<T>会自动转换为&[T]so ,问题是为什么它可以在Vec<T>以及&[T]. 显然,get适用于,那么除了 的实现之外,&[T]它是否还单独实现了?查看文档,似乎不是这样,只有一种实现:https://doc.rust-lang.org/std/vec/struct.Vec.html#method.getVec<T>&[T]get
在下面的代码中,get作用于Vec<T>。
fn first<T: PartialOrd + Copy>(list: Vec<T>) -> T {
*list.get(0).unwrap()
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = first(number_list);
println!("The first number is {}", result);
}
Run Code Online (Sandbox Code Playgroud)
在此代码中,它作用于&Vec<T>(又名&[T]):
fn first<T: PartialOrd + Copy>(list: &Vec<T>) -> T {
*list.get(0).unwrap()
} …Run Code Online (Sandbox Code Playgroud) 这是标准说的:
pub trait PartialEq<Rhs: ?Sized = Self> {
/// This method tests for `self` and `other` values to be equal, and is used
/// by `==`.
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
fn eq(&self, other: &Rhs) -> bool;
/// This method tests for `!=`.
#[inline]
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
fn ne(&self, other: &Rhs) -> bool {
!self.eq(other)
}
}
Run Code Online (Sandbox Code Playgroud)
和链接:https : //doc.rust-lang.org/src/core/cmp.rs.html#207
这是我的代码:
fn main() {
let a = 1;
let b = &a;
println!("{}", …Run Code Online (Sandbox Code Playgroud) 在做rustlings 时standard_library_types/iterators2.rs,我开始想知道如何std::iter::Iterator::map调用它的参数闭包/函数。更具体地说,假设我有一个功能
// "hello" -> "Hello"
pub fn capitalize_first(input: &str) -> String {
let mut c = input.chars();
match c.next() {
None => String::new(),
Some(first) => String::from(first.to_ascii_uppercase()) + c.as_str(),
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想用它
// Apply the `capitalize_first` function to a slice of string slices.
// Return a vector of strings.
// ["hello", "world"] -> ["Hello", "World"]
pub fn capitalize_words_vector(words: &[&str]) -> Vec<String> {
words.into_iter().map(capitalize_first).collect()
}
Run Code Online (Sandbox Code Playgroud)
哪个不编译
error[E0631]: type mismatch in function arguments
--> exercises/standard_library_types/iterators2.rs:24:27
|
11 …Run Code Online (Sandbox Code Playgroud) iterator functional-programming dereference rust trait-objects
rust ×10
async-await ×1
comparison ×1
dereference ×1
iterator ×1
lifetime ×1
mutable ×1
reference ×1
scope ×1
string ×1