google / starlark-go

Starlark in Go: the Starlark configuration language, implemented in Go
BSD 3-Clause "New" or "Revised" License
2.32k stars 212 forks source link

FR: add Clone methods for mutable aggregate types #446

Open brandjon opened 1 year ago

brandjon commented 1 year ago

For *List, *Dict, and *Set, it'd be nice to have convenience methods to shallow-copy them, so an application doesn't have to use an explicit loop or call the Slice method.

adonovan commented 1 year ago

s/shallow/deep/ ?

brandjon commented 1 year ago

I forgot that Java's clone is deep, not shallow, so what I'm talking about would probably be called Copy.

Naming aside, I imagine it's more convenient/straightforward to have a shallow copy operation, since that's what you end up with if you try to copy things straightforwardly in Python and Starlark code (mylist = list(other)), and it's equivalent to the Slice workaround. A deep copy operation is much more difficult to describe, particularly in the presence of application-defined types, so I don't think we can robustly support it without adding an extension point of some kind for application types.

adonovan commented 1 year ago

I see the confusion: the Copy method would create a new List/Dict/Set with the same elements. From Go's perspective, that's a deep copy of the collection data structure (not just a struct copy), but from Starlark's it's a shallow copy, since the elements are the same.