I'm trying construct an array of structs where each instance contains a different function. I want to add these to an array in a loop.
Here's an example:
struct mystruc{F}
σ::F
end
a = [mystruc(relu)]
for i in 1:3
append!(a, [mystruc(identity), ])
end
As a side note, I have the option to preallocate the array I just couldn't figure out how to do with this type of struct.
Each function has a type, which is exclusive to that function:
Here we created the function
x -> xtwice, they are two different functions, so their types are not the same.In your construction of
a, you create an Array of that specific type:So when you push another function, we get an error, because this array can only contain objects of the type
mystruc{typeof(relu)}.Solution
When you construct
a, tell Julia that the array will containmystrucwith any function:and now it works!