Repository navigation
Description
Motivation
Data structures which closely fit a single inheritance model can be very efficiently implemented in C++. Where high performance (both space and time) is crucial there is distinct disadvantage in using Rust for programs which widely use such data structures. A pressing example is the DOM in Servo. For a small example in C++, see https://gist.github.com/jdm/9900569. We require some solution which satisfies the following requirements:
- cheap field access from internal methods;
- cheap dynamic dispatch of methods;
- cheap downcasting;
- thin pointers;
- sharing of fields and methods between definitions;
- safe, i.e., doesn't require a bunch of transmutes or other unsafe code to be usable;
- syntactically lightweight or implicit upcasting;
- calling functions through smartpointers, e.g.
fn foo(JSRef<T>, ...); - static dispatch of methods.
Status
There has been discussion of potential solutions on discuss (http://discuss.rust-lang.org/t/summary-of-efficient-inheritance-rfcs/494) and in several meetings (minutes and minutes).
We clarified the requirements listed above (see the minutes for details) and established that an ergonomic solution is required. That is, we explicitly don't want to discourage programmers from using this feature by having an unfriendly syntax. We also summarised and evaluated the various proposals (again, see the minutes for details). We feel that no proposal 'as is' is totally satisfactory and that there is a bunch of work to do to get a good solution. We established a timeline (see below) for design and implementation. We would like to reserve a few keywords to reduce the backwards compatibility hazard (#342).
Plan
In December the Rust and Servo teams will all be in one place and we intend to make decisions on how to provide an efficient code reuse solution and plan the implementation in detail. We'll take into account the discussions on the various RFC and discuss comment threads and of course all the community members who attend the Rust weekly meetings will be invited. We will take and publish minutes. This will lead to a new RFC. We expect implementation work to start post-1.0. If we identify backwards compatibility hazards, then we'll aim to address these before the 1.0 RC.
RFC PRs
There have been numerous RFC PRs for different solutions to this problem. All of these have had useful and interesting parts and earlier RFCs have been heavily cannibalised by later ones. We believe that RFC PRs #245 and #250 are the most relevant and the eventual solution will come from these PRs and/or any ideas that emerge in the future. For a summary of some of the proposals and some discussion, see this discuss thread.
Activity
brendanzab commentedon Oct 5, 2014
Comment moved to discuss.
why-jay commentedon Dec 23, 2014
What ended up happening? :)
huonw commentedon Dec 24, 2014
That paragraph is unfortunately outdated: we'd actually already postponed all discussion to after 1.0 since we believe any changes/features we will add are backwards compatible and there's a lot of more urgent (I.e. backwards incompatible) work that took priority.
why-jay commentedon Dec 24, 2014
I understand. I'm excited to see what ends up being implemented.
breckinloggins commentedon Feb 13, 2015
One thing I love about rust is that its non-free abstractions are usually explicit. I love knowing that a struct is "just a struct". It would be nice to say that features requiring runtime and fancy "under the hood" data representation support (for some value of fancy) are built from pluggable, orthogonal components.
So how about something like "anonymous composition is inheritance"? The idea would be that
implies a specific struct layout with the requisite syntactic sugar. For simplicity let's suppose that we only allow one anonymous component per struct.
EDIT: It was pointed out to me by @steveklabnik and others that rust has had trait objects since forever. I'll keep the following bit in place and just say that std::raw::TraitObject is the kind of thing I would love to be not only "pluggable" but "leave-out-able", in the sense that if I'm writing an OS and I can't implement that yet, I can tell the compiler that it can't make me any TraitObjects and that it wouldn't be ok for me to use them right now.
For dispatch, it would be nice if we could plug-in and compose the dispatch resolution mechanism. I don't want the "doesn't play well with others" feel of C++ vtables. What if I want to back this part of the language with the Objective-C runtime? Or Glib? The current "personality" of rust feels like this should be possible, in the same way that "give me your allocator function and then I'll let you use boxed things" works.
I guess my main point is that rust is the first language in a long time where I really feel like the modern features of the language don't come with being chained to a runtime layout and functionality set that's given from up on high by the Gods of Rust.
I would love it if the rust team could implement functionality like this while still retaining that ethos.
pcwalton commentedon Feb 13, 2015
Virtual dispatch will of course be explicit under this proposal or any other.
steveklabnik commentedon Aug 27, 2015
It's worth mentioning that @nikomatsakis has been working on this proposal: http://smallcultfollowing.com/babysteps/blog/2015/08/20/virtual-structs-part-3-bringing-enums-and-structs-together/
Merge pull request rust-lang#349 from Idolf/master
sighoya commentedon Mar 11, 2018
What's the state in 2018?
Couldn't we agree to any "inheritance" proposal?
blueridanus commentedon Apr 12, 2018
What happened to @nikomatsakis's proposal?
I'm trying to create a general UI framework for Rust, basically based on push-pull FRP. There's no way to do it, however, because there's no way to model a type hierarchy: enums don't actually "add" types together, and the nodes of enums aren't really types, only tags.
41 remaining items
SOF3 commentedon Jun 14, 2022
I am not sure what the problem encountered in rustc is, but last time i had to work on a flow analysis in Java, I really wished they were enums.
Iron-E commentedon Jun 14, 2022
@mrahhal I made a comment on Reddit about this issue not too long ago. In short, it's not related to struct inheritance, but the fact you can't downcast any-old trait object (e.g.
&dyn Foo) in Rust— only&dyn Anyand&dyn Error(afaik). Hopefully that changes in the future!mrahhal commentedon Jun 14, 2022
@Iron-E Thanks, I didn't know about this. But it's not related to the code reuse issue. Traits unify signatures and are not the answer for code reuse. I'm not saying it should be related to inheritance either, the solution could very well be through composition. In summary, need a code reuse solution (won't repeat what this issue lists as requirements) that also provides the ability to pattern match on type kinds (a type kind's meaning is an impl detail). (But thanks for the downcast pointer, might be useful in certain cases)
It's unfortunate that this has been in stagnation since 2014. Rust is great, but this is one of the biggest blockers if you're modeling certain complex logic that wants some kind of code reuse, without having to resort to an amalgamation mess of unreadable macros.
SOF3 commentedon Jun 16, 2022
I still don't see what's missing with enums. Code reuse through enum delegation could be convenient given the appropriate codegen mechanisms (such as a decl macro derived from a proc macro).
mrahhal commentedon Jun 16, 2022
One example is when you want to restrict types. Imagine building a tree model for a compiler and having specific nodes (IfStatementNode, UnaryExpressionNode, etc) representing the structure, you want a few base node types that reuse some logic, and then you want to store specific node types in other nodes (or simply accept certain types in functions). You can't do any of this in rust today. (yes, I know I can nest structs inside of each other, but people reaching out to Deref hacks is proof this isn't a valid solution for many cases)
The way rustc and servo work around this is by having multiple enums (Statement, Expression, etc) and compromising by restricting to the common denominator enum (Expression for example), but this results in a lot of annoyances throughout the code (it's not strong typed). The problem is not specific to wanting to model intrinsically hierarchical models, but it is a pain there in particular.
And as I just noted above, I don't want macros to solve common reusability needs.
fogti commentedon Jun 16, 2022
@mrahhal a partial solution for this would be combining
enum-derive(or something like that) to expose traits defined for contained types, and introducing a way to flatten enums (so, like kind of inheritance for enums, the enums which "get" (?) inherited from must be exhaustive; similar to the "mixin" concept in other languages), like:mrahhal commentedon Jun 16, 2022
@zseri I've explored many solutions including this. It's still far from what I want. Yes you can easily create a visitor that exposes a "flattened" match on the type, but that alone doesn't solve it. Even if
Exprcontains aUnaryExprvariant,UnaryExpritself is not anExpr. This means I can't share common functionality (again, without resorting to messy macros and a lot of boilerplate). I also wouldn't say this is equivalent to mixins. You're just nesting types inside other types here, whereas mixins are pretty much composition of logic inside the same type.Right now I implement something similar to what rustc does, multiple enums and a few macros to handle some of the logic reuse (no tool can semantically parse macros so somehow we're back to using
eval("{code as a string}")everywhere). I tried every kind of workaround you can think of, none can replace a proper code reuse feature.wandercn commentedon Jun 19, 2022
我认为写一个完整一点的例子比较起来比较直观, @ibraheemdev @Iron-E @mrahhal @zseri
以下是golang代码通过结构体内嵌实现的属性和方法复用代码方式,这是golang面向对象的处理方式,确实很方便。怎么转换到 rust的 trait方式复用代码呢?
rust中实现的时候把golang中的baseRequest结构体的方法,抽象到trait BaseRequestExt中,trait BaseRequestExt中的 fn base(&self) 和 fn base_as_mut(&mut self) 方法,需要在每次复用的时候重写。其他的代码直接复用trait BaseRequestExt中的方法,我觉得还是非常高效的。
详细的对照代码如下:
fogti commentedon Jun 19, 2022
@Iron-E regarding
although this isn't solved automatically, the
downcast-rs,as-any(the second crate, written by myself, is a bit simpler, and less powerful) crates partially solve this.SOF3 commentedon Jun 21, 2022
@wandercn The question is, why do we need to use
SendSmsRequestitself as aBaseRequest? Why can't users just callrequest.base()directly?wandercn commentedon Jun 21, 2022
@SOF3
就是为了实现跟golang一样的内嵌结构体,直接组合复用代码,组合看成一个整体。
12101111 commentedon Jun 21, 2022
@wandercn You can use this crate https://crates.io/crates/delegate
SOF3 commentedon Jun 22, 2022
@wandercn That's what I'm saying, why do we want composite structures? How is
request.base_func()any better thanrequest.base.func()?Even in OOP languages like Java, it is typically considered an antipattern to have deep hierarchies of inheritance. Composite structures do not save us from all the issues of inheritance. Having
basenested deeply inside is probably not that sensible anyway.Instead of
Why not
? At least in that case it is more explicit that
Fooitself should be used as a component instead of a request itself, because aBarrequest is indeed not aFoorequest, and it would be confusing for aBarrequest to contain aFoorequest. I am not sure whether self-descriptive type system is a popular concept in the Go language, but for Rust, many APIs are already clear enough what they intend to do just by looking at the type signature, so if you have a function that accepts aHorseRequest, you probably expect that an actual, self-containedHorseRequestwas sent, and if someone actually sent aWhiteHorseRequestthat contains aHorseRequest, you would end up with a condition where 白馬非馬. One confusing example is like this:handle_horseexpects to assign a color to a horse request. Originally it couldn't go wrong. But since aNewWhiteHorseRequestalso contains aNewHorseRequest, we end up allowing people to misuse thehandle_horseAPI for white horse requests, which should originally be impossible.To conclude, having a type contain a type that contains another type (i.e. more than one level of composition) while the outermost type has direct relationship to the innermost type is an antipattern, no matter we have code reuse (through inheritance or struct composition) or not. This antipattern just becomes typically less obvious in Java, Go, etc. because people are too used to the ambiguous information represented by type information, but becomes more apparent in Rust because people are writing code "correctly" (my subjective opinion) such that self-explanatory function signatures become possible.
dbsxdbsx commentedon Mar 15, 2023
Using this crate is still the best way I found to reuse code, at present.
workingjubilee commentedon Jan 1, 2025
My understanding is that T-lang is not interested in following discussion on the RFCs repo that is not actual RFC. This proposal seems interesting but is unfortunately in the form of an issue instead of an RFC. If someone wanted to pursue it as an RFC, they should open it as a PR (following the template where useful, as usual).