小编osa*_*amu的帖子

为什么不能将 &str 传递给接受 &dyn Display trait 对象的函数?

我正在阅读一本 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)

为什么这会失败而第二次调用有效?

rust trait-objects

7
推荐指数
1
解决办法
366
查看次数

容器内的颤动容器

这些天我正在练习飘动的容器,而我想出的这个例子简直令人惊讶

我把尺寸为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)

我希望在一个更大的橙色盒子里面放一个小蓝盒子.

有人能解释为什么吗?

flutter

5
推荐指数
1
解决办法
1509
查看次数

不能把"自我"借给不可变因为"self.chars"也被借用为可变的

我需要对一个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)

rust

0
推荐指数
1
解决办法
272
查看次数

标签 统计

rust ×2

flutter ×1

trait-objects ×1