Zero-trait generics

OOP is not an universal paradigm and is just another tool.
I want to create generic functions which operate on certain structs which have certain fields.
Why not make the compiler check the type of a struct for an existing field?

With current rust, the situation is the following:

fn walk<T: HasSpeed>(walker: T, time: f32) -> f32 {
    walker.speed() * time

trait HasSpeed {
    fn speed(&self) -> i32;

struct Human {
    speed: i32,

impl HasSpeed for Human {
    fn speed(&self) -> i32 {

Now that is a quite chunky piece of code. Imagine how much of that one would need for all the properties a human has. Insane. What if there was a compile-time check for a fields' presence in a struct?

pub fn walk<T.speed: f32>(walker: T, time: f32) -> f32 {
    walker.speed * time

This wouldn't even need any traits or methods!

There are some languages that do this, but honestly I think it would make for more fragile code. Traits are a more robust abstraction.


Why not make functions that operate on fields, not on struct. Structs are a relation or a context between fields, if you don't care about the relations or the context there is no need to take the structure as argument

What you're seems to ask is to have a kind of open objects as oCaml do, I don't think that is possible in Rust or how to emulate that behavior

I'd say you're feeling a bit of resistance because you're trying to use the wrong tool for the job.

A big part of traits is in specifying behaviour, not structure. You can kinda fudge structure constraints by using getters or "view structs" (imagine returning a type which contains references to the fields you need), but the language wasn't really designed with structural typing in mind.

For future reference, I the term for what you're referring to is "structural typing" and it's commonly used in languages like TypeScript or Go. It's also often referred to as "duck typing" when done at runtime (e.g. by doing a property access and throwing an exception or returning a singleton value like JavaScript's undefined).

It sounds like you're asking for the compiler team to implement some form of structural typing because it would make it easier to write programs in the style you like.

While I can see the benefits and how it could lead to more expressive, concise code, be prepared for a fair amount of push back... To properly support it you'd need to rewrite large swathes of the type system and borrow checker, plus loads of documentation.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.