我正在阅读一本 Rust 书,但我对这个例子感到困惑:
use std::fmt::Display;
fn main() {
test("hello");
test2("hello")
}
fn test(s: &dyn Display) {
println!("{}", s);
}
fn test2(s: &str) {
println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)
&'static str作为特征对象传递失败:
use std::fmt::Display;
fn main() {
test("hello");
test2("hello")
}
fn test(s: &dyn Display) {
println!("{}", s);
}
fn test2(s: &str) {
println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)
为什么这会失败而第二次调用有效?
这些天我正在练习飘动的容器,而我想出的这个例子简直令人惊讶
我把尺寸为50x50的容器放在200x200的容器内.奇怪的是内部容器扩展到200x200,即使它有50x50的严格约束.
这是代码
Container(
width: 200.0,
height: 200.0,
color: Colors.orange,
child: Container(
width: 50.0,
height: 50.0,
color: Colors.blue,
),
)
Run Code Online (Sandbox Code Playgroud)
我希望在一个更大的橙色盒子里面放一个小蓝盒子.
有人能解释为什么吗?
我需要对一个struct字段的不可变访问和对另一个struct字段的可变访问,但它们必须相互堆叠.我多次遇到这个问题而且我不知道如何解决这个问题.
use std::collections::HashMap;
struct Bar;
impl Bar {
fn get(&self) -> i32 {
100
}
}
struct Foo {
chars: HashMap<char, i32>,
b: Bar,
}
impl Foo {
fn run(&mut self) {
self.chars.entry('c').or_insert_with(|| self.b.get() * 100);
}
}
fn main() {
let mut m = Foo {
chars: HashMap::new(),
b: Bar,
};
m.run();
}
Run Code Online (Sandbox Code Playgroud)
error[E0502]: cannot borrow `self` as immutable because `self.chars` is also borrowed as mutable
--> src/main.rs:16:46
|
16 | self.chars.entry('c').or_insert_with(|| self.b.get() * 100);
| ---------- ^^ ---- …Run Code Online (Sandbox Code Playgroud)