I want to add a Function inside a Struct, Because I will read from a user provided CSV file that tell me what function to use.
In below example, I had a “sound” function inside each struct, that can perform different operations.
However, when I do “code_warntype”, I can clearly see Type unstable when reaching the function part.
abstract type Operate end
struct Cut <: Operate
member::String
sound::Function
end
Cut() = Cut("t", sum)
struct Push <: Operate
member::Int
sound::Function
end
Push() = Push(1, mean)
struct Roll <: Operate
member::Symbol
sound::Function
end
Roll() = Roll(:a, max)
a = Roll()
b = Push()
c = Cut()
function test(a::Operate)
arr = [1,2,3,4,5]
b = a.sound(arr)
println(b)
end
@code_warntype test(a)
@code_warntype test(b)
@code_warntype test(c)
code_warntype:
8 ─ %23 = (Base.getfield)(a, :sound)::Function
│ %24 = (%23)(%2)::Any
│ %25 = (Main.println)(%24)::Any
└── return %25
How to make the Function inside the Struct Type-stable?