使用不同的模式运行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) 我在将 json 反序列化为结构时遇到问题。
这是模拟我的问题的代码:
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender };
extern crate serde_json;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[derive(Deserialize, Debug)]
struct Foo<'a> {
a: u32,
b: u32,
c: &'a str,
}
fn main() {
let (msg_tx, msg_rx): (Sender<Foo>, Receiver<Foo>) = mpsc::channel();
{
let js = r#"{"a":33, "b":44, "c": "ss"}"#; // initially I have a json String, here I simulate a problem
let js_string = String::from(js);
let f = test(js_string.as_str());
msg_tx.send(f);
}
}
fn test(js: &str) -> Foo { …Run Code Online (Sandbox Code Playgroud) 我经常看到像这样返回 Result<(), Error> 的函数或方法:
fn f() -> Result<(), Error> {
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
换句话说,这种返回不返回任何内容或错误。为什么在这种情况下使用 Result 而不是 Option ?我认为 Option 会更合适,因为它有效地返回 None 或值,在我们的示例中 - None 或错误。
fn f() -> Option<Error> {
None
}
Run Code Online (Sandbox Code Playgroud)