Skip to content

Instantly share code, notes, and snippets.

@Perelandric
Last active August 17, 2016 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Perelandric/a28b82e35444314de1ea4ad08aeccb51 to your computer and use it in GitHub Desktop.
Save Perelandric/a28b82e35444314de1ea4ad08aeccb51 to your computer and use it in GitHub Desktop.
Trying to make generic class with clone method
actor Main
new create(env: Env) =>
let foo_layers = Layers[Foo] // `Layers` of `Foo`
// The important part is that it defines a clone()
trait MyTrait[U]
new create()
fun clone(): U
// One of several classes that will implement MyTrait
class Foo is MyTrait[Foo iso^]
new create() => None
fun clone(): Foo iso^ => recover Foo end
// A generic type that holds an Array of the respective MyTrait types, like Foo
class Layers[T: MyTrait[T]]
var values: Array[T] = Array[T]
fun clone(): Layers[T] =>
// The clone we're creating
let c = recover Layers[T] end
var i = USize(0)
let len = values.size()
// The array for the clone
let a = recover Array[T](len) end
// Clone each item in the original array to the new array
while i < len do
try
let item: T = values(i).clone()
a.push(recover ref item end)
end
i = i + 1
end
// Put the new array of cloned items on the main clone
c.values = consume a
c
@Perelandric
Copy link
Author

Here are the highlights:

  • MyTrait defines a clone() that should ultimately return an iso^ copy of whatever is implementing the trait
  • Foo is a class that implements MyTrait
  • Layers is a generic class that simply wraps an Array of T: MyTrait

The trouble is that I'm trying to give Layers its own clone() method that performs a deep clone. While the clone() is meant to produce an iso, it'll ultimately be placed into the Array as a ref.

Note that the Array in Layers holds T: MyTrait, not simply MyTrait.

What I show above is one of my earlier, simpler attempts, which is clearly wrong. Some guidance would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment