# Type Unstable: Function within a Struct

**URL:** https://discourse.julialang.org/t/type-unstable-function-within-a-struct/31110
**Category:** New to Julia
**Created:** [November 15, 2019, 1:52am UTC](https://discourse.julialang.org/t/type-unstable-function-within-a-struct/31110 "2019-11-15T01:52:57Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Eric\_Chen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/eric_chen/32/5992_2.png) [@Eric\_Chen](https://discourse.julialang.org/u/Eric_Chen)
#### Post date: [November 15, 2019, 1:52am UTC](https://discourse.julialang.org/t/type-unstable-function-within-a-struct/31110/1 "2019-11-15T01:52:57Z")

</div>

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.

```julia
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:

```julia
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?

---

<div class="post-metadata">

### Author: ![jkbest2](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jkbest2/32/7350_2.png) [@jkbest2](https://discourse.julialang.org/u/jkbest2)
#### Post date: [November 15, 2019, 2:20am UTC](https://discourse.julialang.org/t/type-unstable-function-within-a-struct/31110/2 "2019-11-15T02:20:19Z")

</div>

Every function has its own type (`Function` is an `abstract type`), so you want to parameterize your `struct` by that type. Something like

```julia
struct Cut{F}
  member::String
  sound::F
end

```
