There is a simple example:
struct MyStruct
a: int
b: int
def my_proc(): unowned list of MyStruct
var result = new list of MyStruct
var my_struct = MyStruct()
for var i = 1 to 10
my_struct.a = i
my_struct.b = i*i
result.add(my_struct)
return result
init
pass
in case of compilation of this code, there is an error: "Local variable with strong reference used as return value and method return type has not been declared to transfer ownership". How to change a code that compilation took place successfully?
A Genie list is really a Gee.List<T>
in "disguise" which is a class type, so it will be reference counted.
Also a type inferred var
variable is currently always an owned variable (there is a bug report about this in the Vala bug tracker).
So result
a strong reference to a class instance. You can't return that as an unowned reference.
I'd strongly advice you to use a class instead of a struct for MyStruct
.
Otherwise you will have memory management problems (structs are not reference counted).
You don't have to worry about copying and ownership then:
class MyStruct
a: int
b: int
def my_proc(): list of MyStruct
var result = new list of MyStruct
for var i = 1 to 10
var my_struct = new MyStruct()
my_struct.a = i
my_struct.b = i*i
result.add(my_struct)
return result
init
pass
Edit: If you want the list to contain multiple values, you have to allocate my_struct inside the loop as well! I have updated my code to reflect that.