Cassie's profile picture

Published by

published

Category: Web, HTML, Tech

rust pt 1

in a lot of langages, reflection is able to access all the fields of an object, no matter if they are private or not. reflection just seems to be soprt of special, and able to bend the rules here and there.

there are, of course, some restrictions to this, but, in general, the rules around reflection tend to be less strict.

coming from a high-level language with reflection, it seems resonable to assume that this is a natural part of reflection. u can set the value of a private field in C#:

class Test {
  private float _secret;
}
void SetSecret(Test test, float val) {
  typeof (Test).GetField("_secret", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(test, val);
}

In Java:

class Test {
	private float _secret;
}
class Spy {
	void SetSecret(Test test, float val) {
    	Field field = getField(test.getClass(), “_secret”);
    	// Oh, this field is inaccessible?
    	field.setAccessible(true);
    	// Now it is accessible.
    	field.set(test, val);
	}
}

this is even easier in other langwages, like python or lua; here, the ideea of privacy is more of a courtesy than a rule.

class TestClass:
	__secret = "Spooky"
# No privacy in snake-land...
setattr(a, '_TestClass__secret',val)
# This works too :)
test._TestClass__secret = val
test.secret = val;
-- In Lua, everything is just a table.
test["secret"] = val;

doing things this way is often seen as an anti-pattern, since it breaks encapsulation. thouh it is useful in certain scenarios-for ex, when serializing and deserializing data. after all, requiring all serializable / deserializable fields to be public would probably bring more trouble than it is worth.

tthings can’t work this way in rust, no matter what reflection API ends up being impleminted. let me show you why.


0 Kudos

Comments

Displaying 0 of 0 comments ( View all | Add Comment )