Bit of a question:

As a bit of a quarantine project I'm working my way through the book "Writing an interpreter in go" but I'm writing it in rust. (Stops me copy-pasteing / skimming)

His AST data structure is based on interfaces that have standard properties and methods. I decided to use structs for this, but structs can only have methods.

Whats the best way to deal with this in rust? Is there a way to define standard properties in a type? Or should I use a mix of enums and traits?


I don't fully follow what you'd like to do (maybe because I don't know ?) but the way I'd probably approach this in is with a struct with enum fields. Something like

struct Node {
token: Token,

enum Token {


But I'm not quire sure; maybe others will way in with better advice.


Yeah, my go is also pretty lacking, just enough to follow reading it. I've written an example in TypeScript to make it clearer for you.

Can you have generic structs that are implemented by other structs?

In your example I would need to do

impl Node for LetStatement {


(but impl is for traits only? I'll look it up)



> but impl is for traits only?

No, you can implement methods directly on structs/enums. Really, that's the *only* place you can implement methods – when you declare a trait, you can optionally provide a *default* implementation of a method, but that method is only available after you implement the trait for a struct/enum

> Can you have generic structs that are implemented by other structs?

No, that would basically be inheritance, which doesn't use.


> > but impl is for traits only?

Yes, I meant `impl _ for` is for traits only, sorry for being unclear.

> No, that would basically be inheritance

Yeah, I guess I should stop read further into the book to see how he's using the data structure, then come up with a more rust-like structure to do this with. So far I've been mostly reproducing the code, then modifying it to be more rust-y at the end of a chapter.

Sign in to participate in the conversation

Fosstodon is an English speaking Mastodon instance that is open to anyone who is interested in technology; particularly free & open source software.