# Use function on type parameter to decide struct field type at compile time

**URL:** <https://discourse.julialang.org/t/use-function-on-type-parameter-to-decide-struct-field-type-at-compile-time/89172>\
**Category:** General Usage\
**Tags:** performance, type\
**Created:** [October 24, 2022, 2:55am UTC](https://discourse.julialang.org/t/use-function-on-type-parameter-to-decide-struct-field-type-at-compile-time/89172 "2022-10-24T02:55:25Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![HashBrown](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hashbrown/32/43601_2.png) [@HashBrown](https://discourse.julialang.org/u/HashBrown)\
**Post date:** [October 24, 2022, 4:47am UTC](https://discourse.julialang.org/t/use-function-on-type-parameter-to-decide-struct-field-type-at-compile-time/89172/4 "2022-10-24T04:47:07Z")

</div>

Actually based on the output of `@code_warntype` using a `for` loop does still yield type instability because the type of `f` is different on each iteration.

Replacing the for loop with individual indexing:

```julia
s += b.foos[1].a
s += b.foos[2].a

```

yields completely type stable code. Look at this interesting thread for interesting general approaches that don’t involve hardcoding [Type stability while looping over Tuple](https://discourse.julialang.org/t/type-stability-while-looping-over-tuple/83272). Namely recursion and the Unrolled.jl package

---

_[View the full topic](https://discourse.julialang.org/t/use-function-on-type-parameter-to-decide-struct-field-type-at-compile-time/89172)._
