I have an sequence keep an list of the reference of base object(ref to inherited object), and I want to return an base object, how can I do this?
type
FooType = enum A, B
Foo = object of RootObj
ft: FooType
FooA = object of Foo
FooB = object of Foo
proc `$`[T](a: ref T): string = $a[]
proc gen_list(): seq[ref Foo] =
result.add (ref FooA)(ft: A)
result.add (ref FooB)(ft: B)
# I wish to return an Foo, rather than ref Foo
# But no easy way
# Any work around?
proc get_item(s: seq[ref Foo], index: int): Foo =
s[index][] # this will fail with invalid object assignment
let s = gen_list()
echo get_item(s, 0)
Well, it used to be possible. A better message for the error would be 'Object slicing is not allowed'.
Then, as of now, the only possible way (that Im aware of, not even cast works here) is to manually copy the values:
proc get_item(s: seq[ref Foo], index: int): Foo =
let foo = s[index][]
result.ft = foo.ft