3 ms·
Other languages can definitely do it: Ruby: class X attr_accessor :y end Crystal (full working example): class Y end class X
by dorianm 10y ago
Other languages can definitely do it:
Ruby:
class X
attr_accessor :y
end
Crystal (full working example):
class Y
end
class X
def initialize(y : Y)
@y = y
end
def y
@y
end
end
y = Y.new
x = X.new(y: y)
puts x.y
- willvarfar 10y agoThe article is not about returning a reference to a struct member, its about returning a reference to something on the stack rather than heap.
- imron 10y agoAnd crucially, enforcing that no references to the returned member will outlive the containing struct.
- topspin 10y agoRust ownership applies to heap allocated objects as well; if you return a reference to a member of a heap allocated struct that reference cannot outlive the struct allocation. The point of the article is more general than "stack vs heap;" other languages are either incapable of expressing a reference to a member of a heap allocated struct or incapable of ensuring the memory safety of such a reference.
- willvarfar 10y agoAs the article notes, garbage-collected languages can ensure the memory safety of a pointer into a heap object.
- TuringTest 10y agoBut not at compile time, which is what Rust provides.
- qznc 10y agoAny language where the X thing is managed by a garbage collector (and you cannot manually delete it anyways) is just as safe as Rust. What only Rust can do is to check your manually memory-managed stuff for correctness (conservatively).
- roca 10y agoI looked up Crystal. Crystal "class" objects are heap allocated, so in this example "y" is allocated as a separate heap object to the X. As I outlined in my post, that isn't what I was asking for.