Maybe the question is not well written, but it’s because I do not really know what’s happening in here. I’m learning Rust, I’m doing pretty good, but this is the second time that stomp with this.

First, I thought that only the Add trait would be enough, but the LSP keep saying me this if I do not add the “restriction”, as far as I know.

What I do not get is what <Output = T> is. I know that is using the type T, but why it is assigned to Output?

The first time that I saw something similar was in the Rust book that comes with rustup, just look at the next function signature

Thank you for you help, you are awesome.

  • Anselm "Two Sheds" Schüler@ieji.de
    link
    fedilink
    arrow-up
    8
    arrow-down
    1
    ·
    15 days ago

    @capuccino You’re not assigning anything. The Output = T is expressing a constraint. It’s saying that the addition of T has to result in T again. A type can implement Add with any output type it wants.

    • oni ᓚᘏᗢ@lemmy.worldOP
      link
      fedilink
      arrow-up
      1
      ·
      15 days ago

      I see. How can I define my own constraints in traits? Maybe seeing how to, I can full understand what’s happening behind

      • Anselm "Two Sheds" Schüler@ieji.de
        link
        fedilink
        arrow-up
        3
        arrow-down
        1
        ·
        15 days ago

        @capuccino

        A trait can have an associated type. You write this “trait Foo { type Bar; }”. Then, when you implement the trait, you have to specify this type, with “type Bar = Something;”. This is different from the trait itself being generic, because there can only be a single associated type, so you can’t implement the trait multiple times with different associated types.

        • Anselm "Two Sheds" Schüler@ieji.de
          link
          fedilink
          arrow-up
          2
          arrow-down
          1
          ·
          15 days ago

          @capuccino

          Then, when you write somewhere that some type satisfies a trait, like “T: Foo”, and Foo has an associated type, you can further specify that not only does T need to implement Foo, but that the associated type satisfies some criteria.

          You can do this two ways:
          “Foo<Bar = Something>” says it has to be something specific,
          “Foo<Bar: Baz>” says that it has to implement another trait

          • oni ᓚᘏᗢ@lemmy.worldOP
            link
            fedilink
            arrow-up
            1
            ·
            15 days ago

            Amazing, so I can keep still using traits as constraints rather than types. I understand know. Hehehe, this is something that has been in my head since days ago