Implementing equality of lox runtime objects (Rust)

I finished the interpreter challenge but then when going back through my code to clean it up, I noticed I get this wrong. Curious if others have run into this too.

fun f() {}

var g = f;

print (f == g);

among other cases. It seems like this is probably pretty easy to get right in Java because the semantics are pretty similar. But as I understand it, Rust doesn’t really encourage you to ask if two objects are actually “the same object” (like Java ==) but only if they’re considered equal according to however you implemented the Eq trait (like Java .equals()). And if you derive it you can end up with two objects being “equal” because they look identical, but according to the Lox semantics they should be considered different objects.

1 Like

Hey @MatrixFrog, you might be able to do pointer identity comparison in Rust, depending on how you’re representing functions.

I was just perusing the docs for Rc and came to the same conclusion :relieved_face: will have to give it a try soon.

Currently a lox runtime value is

enum Value {
  Boolean(bool),
  Number(f64),
  ...
  Function(LoxFunction),
  Instance(Rc<Instance>),
}

so I would need to put my LoxFunctions in Rc’s as well. Probably good to do anyway since a LoxFunction::clone could get expensive.

1 Like

Looking good! :grin:

1 Like

I ended up going a bit further with some help from reddit. I knew about the newtype pattern but it didn’t immediately occur to me to use it here.

2 Likes

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