AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 77907126
Accepted
Fee
Fee
Asked: 2024-01-30 22:31:28 +0800 CST2024-01-30 22:31:28 +0800 CST 2024-01-30 22:31:28 +0800 CST

如何从函数返回“impl Display”

  • 772

我正在努力了解如何正确实现结构的任何类型的替代显示或特征。

struct Fraction {
  numerator: u32,
  denominator: u32
}

impl Fraction {
  fn unicode(&self) -> impl Display {
   // should I use named function or Closure?
   // Where does f come from?
   // can I re-use self?
   // How can I implement a trait that has multiple required functions or `type Output =`?
    fn fmt(&self, f: std::fmt::Formatter) -> std::fmt::Result {
       write!("{}⁄{}", self.numerator, self.denominator)
    } // <- this returns `()`
  }
}

这是行不通的,因为fn fmt作为函数定义,不会返回任何内容。使用未命名的闭包:

impl Fraction {
  fn unicode(&self) -> impl Display {
   // should I use named function or Closure?
   // Where does f come from?
   // can I re-use self?
   // How can I implement a trait that has multiple required functions or `type Output =`?
    |s: &Self, f: std::fmt::Formatter| -> std::fmt::Result {
       write!("{}⁄{}", self.numerator, self.denominator)
    } // <- this returns `()`
  }
}

// somewhere else:
impl Display for Fraction {
  fn fmt(&self, f: std::fmt::Formatter) -> std::fmt::Result {
    write!("{}/{}", self.numerator, self.denominator)
    //        ^-- ASCII '/'
  }
}

说:

error[E0277]: `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}` doesn't implement `std::fmt::Display`
   --> src/fraction/generic_fraction.rs:418:39
    |
418 |     fn display_mixed<'a>(&'a self) -> impl 'a + fmt::Display 
    |                                       ^^^^^^^^^^^^^^^^^^^^^^ `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}` cannot be formatted with the default formatter
    |
    = help: the trait `std::fmt::Display` is not implemented for closure `{closure@src/fraction/generic_fraction.rs:422:9: 422:57}`
    = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead

类似问题:

  • 返回迭代器(或任何其他特征)的正确方法是什么?
  • impl用作函数的参数类型或返回类型时意味着什么?

与返回迭代器(我发现的大多数文档都是关于此的)相反,我试图在函数块中实现我的特征。因此我找不到文档。也许这是错误的做法/思考方式?

rust
  • 1 1 个回答
  • 52 Views

1 个回答

  • Voted
  1. Best Answer
    Aurel Bílý
    2024-01-31T01:14:34+08:002024-01-31T01:14:34+08:00

    正如 @cafce25 在评论中指出的那样,您必须返回实现该特征的东西,这在 Rust 中意味着您需要有一个实现该特征的类型的实例。但您仍然可以从签名和导出类型中“隐藏”这一点,例如通过在函数中声明类型:

    fn foo() -> impl std::fmt::Display {
        struct Example;
        impl std::fmt::Display for Example {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "hi")
            }
        }
        Example
    }
    
    fn main() {
        let d = foo();
        println!("{d}"); // prints "hi"
    }
    

    返回的实例必须携带足够的数据,以便其Display实现能够实际运行。在Example上面,没有数据(Example实际上是ZST),因为fmt实现只是将常量字符串写入格式化程序。

    但更现实的是,您将需要一些实施数据,例如Fraction:

    #[derive(Clone)]
    struct Fraction {
        numerator: u32,
        denominator: u32
    }
    
    impl Fraction {
        fn unicode(&self) -> impl std::fmt::Display {
            struct FractionAsUnicode(Fraction);
            impl std::fmt::Display for FractionAsUnicode {
                fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                    write!(f, "{}⁄{}", self.0.numerator, self.0.denominator)
                }
            }
            FractionAsUnicode(self.clone())
        }
    }
    

    如果您想避免克隆并仅通过共享引用捕获原始部分(因为生成的对象只需要在打印调用期间存在),您可以这样做:

    fn unicode(&self) -> impl std::fmt::Display + '_ {
        struct FractionAsUnicode<'a>(&'a Fraction);
        impl<'a> std::fmt::Display for FractionAsUnicode<'a> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}⁄{}", self.0.numerator, self.0.denominator)
            }
        }
        FractionAsUnicode(self)
    }
    

    在这里,我们声明了返回的“隐藏”对象的生命周期(即赋予函数'a的原始引用的生命周期),我们也必须在块中拼写出来。这是带有引用的结构的标准。有点令人惊讶的是返回类型中添加了额外的内容。如果没有这个,编译器会抱怨:“捕获未出现在边界内的生命周期的隐藏类型”。也就是说,即使我们实际上没有在签名中说明生命周期,但返回实例的生命周期与原始实例的生命周期之间存在联系,即返回实例的生命周期不能比原始实例的生命周期长。Fractionunicodeimpl+ '_impl std::fmt::DisplayunicodeFraction

    对您在评论中提出的问题的简短回答:

    • 多个函数或关联类型怎么样,例如-> impl Iterator<Item = i32>?由于您必须有一个完整的impl特征块,因此您可以像往常一样声明所有函数和关联的类型。
    • 我可以重复使用self吗?不,如上所示,您需要捕获引用、克隆数据或将所需的一些数据提取到返回的实例中。

    最后,让我指出这-> impl SomeTrait并不意味着该函数返回一个特征对象(如-> Box<dyn SomeTrait>)。例如,该函数不能从不同分支返回不同的实现SomeTrait。该语法仅意味着存在一个实现该特征的类型,但您不会从签名中看到该类型。

    • 3

相关问题

  • 在匹配内重用函数时,匹配臂具有预期的不兼容类型

  • match 语句中的 Rust 类型转换

  • 如何强制匹配的返回类型为()?

  • 原始表示中的 Rust 枚举

  • 有没有办法直接简化 Result<String, VarError> 中 Ok("VAL") 的匹配

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve