gdnative-book icon indicating copy to clipboard operation
gdnative-book copied to clipboard

Deciding between `&T` and `TRef<T>`

Open bluenote10 opened this issue 2 years ago • 4 comments

In general godot-rust allows to use e.g. either owner: &Node or owner: TRef<Node> on exported methods, as noted in the Class registration section:

The parameter can be a shared reference &T or a TRef<T>.

Unless I have missed something, the book doesn't go into details why one would chose one over the other. In practice this means that most developers go for &T because it's simpler. This is probably the reason why many people run into problems when trying to set up signals, in particular because this example suggest that passing owner should just work. Searching the discord history shows many cases of failed attempts to get signal connection to work, because owner.connect takes a target: AsArg which only works with owner: TRef<T> but not with owner: &T (unless falling back to unsafe { owner.assume_shared() }). I'm not sure if this limitation is by design or can perhaps be avoided eventually (c.f. https://github.com/godot-rust/godot-rust/issues/749). So far this is the only difference I'm aware of, but there may be further differences. Regarding the book I'd suggest:

  • In case one form is a strict superset of the other, the book should probably recommend using only the more powerful one. I.e, if the AsArg limitation is the only difference, it would make sense to recommend using TRef<T> because it can do strictly more than &T.
  • If there are things that can only be done by one form, but not by the other and vice versa, it would be nice to list these pros/cons of both forms to help with the decision.

bluenote10 avatar Nov 13 '21 10:11 bluenote10