#Help with baby's first generics

13 messages · Page 1 of 1 (latest)

warm merlin
#

Hi all! I've just started learning rust, coming from C++ (and as an extra C#) backgrounds. I'm currently reading the Rust Programming Language book (https://doc.rust-lang.org/book) and I'm at the generics + traits + lifetimes part. I tried to do some own generic programming in rust but I quickly hit a roadblock (probably because I haven't yet read through the whole book). So the problem itself is given a type and its implementation:

struct Rect<T> {Width: T, Height: T }
impl<T> Rect<T> {
    pub fn area(&self) -> T { self.Width * self.Height }
}

will not compile because we don't know if T can be even multiplied and if we constraint T to std::ops::Mul as the compiler suggests we don't know whether T * T still returns another T. Now in C++ I would just do a templates with deduced return type:

template <typename T>
concept Mul = requires(T&& t) { t * t; };

template <Mul T>
struct Rect {
   T Width; T Height;
   auto area() const { return Width * Height; }
};

But that auto return type is of course not a thing in rust. So my question is how would I design a similar generic Rect struct with rust?

misty magnet
#

i mean isnt concepts a direct copy of rust traits/haskell typeclasses

#

anyways, rust doesnt like type inference at the API boundaries

#

if i know my limited C++ info right, that code is equivalent to:

struct Rect<T: Mul> {
    width: T, // as per style guidelines of Rust :p
    height: T,
}

impl<T: Mul> Rect<T> {
    fn area(self) -> <T as Mul>::Output {
        self.width * self.height
    }
}
#

(note that <T As Mul>::Output doesn't necessarily mean it will output a T)

warm merlin
#

as per style guidelines of Rust :p
fair fair 😄

misty magnet
#

traits are direct copy of haskell type classes

#

-influences

wicked palmBOT
#

Influences

Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed):

  • SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation
  • C++: references, RAII, smart pointers, move semantics, monomorphization, memory model
  • ML Kit, Cyclone: region based memory management
  • Haskell (GHC): typeclasses, type families
  • Newsqueak, Alef, Limbo: channels, concurrency
  • Erlang: message passing, thread failure, linked thread failure, lightweight concurrency
  • Swift: optional bindings
  • Scheme: hygienic macros
  • C#: attributes
  • Ruby: closure syntax, block syntax
  • NIL, Hermes: typestate
  • Unicode Annex #31: identifier and pattern syntax
misty magnet
#

(note that you can impl your custom traits on types you do not own)

warm merlin
#

nice, I do like the language so far, it solves a lot of foot-guns you have in C++

warm merlin