xiaopanzi
V2EX  ›  Rust

Rust 使用泛型作为返回值的问题

  •  
  •   xiaopanzi · May 7, 2021 · 2593 views
    This topic created in 1831 days ago, the information mentioned may be changed or developed.

    参考The Book的例子,有一个疑问,impl Summary作为返回值是否是一种语法糖?

    我试着这样写:

    pub fn test_return<T: Summary>() -> T {
        Tweet {
            username: String::from("Jim"),
            content: String::from("learning trait"),
            reply: false,
            retweet: true,
        }
    }
    

    但是,编译通不过:expected type parameter T, found struct Tweet。所以上述的写法和直接返回impl Summary的区别到底是什么?

    3 replies    2021-05-11 07:38:13 +08:00
    sosilver
        1
    sosilver  
       May 7, 2021 via Android
    泛型参数是由 caller 决定的,所以函数里没法返回 concrete type ( Tweet 不是 T )。返回位的 impl Trait 类型,由函数实现决定,只是不写出来(可能写不出来)。
    h404bi
        2
    h404bi  
       May 7, 2021
    写成 pub fn test_return<T: Summary>() -> T;,caller 就能假定可以 test_return::<NonTweet>() -> NonTweet (假设 NonTweet 实现了 Summary )这样调用了,但实际上函数内只返回 Tweet 了,不是 generic 。

    返回位这里的 impl Trait 实际上是一个 Existential type,跟写成 T 的 Generic type 不同。
    abscon
        3
    abscon  
       May 11, 2021 via iPhone
    参数里的 impl Trait 是语法糖,但返回值里的 impl Trait 不是语法糖
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3505 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 11:31 · PVG 19:31 · LAX 04:31 · JFK 07:31
    ♥ Do have faith in what you're doing.