# Dynamically assign variables in a function

**URL:** <https://discourse.julialang.org/t/dynamically-assign-variables-in-a-function/34833>\
**Category:** General Usage\
**Tags:** question\
**Created:** [February 18, 2020, 9:48pm UTC](https://discourse.julialang.org/t/dynamically-assign-variables-in-a-function/34833 "2020-02-18T21:48:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![linwaytin](https://avatars.discourse-cdn.com/v4/letter/l/898d66/32.png) [@linwaytin](https://discourse.julialang.org/u/linwaytin)\
**Post date:** [February 18, 2020, 9:48pm UTC](https://discourse.julialang.org/t/dynamically-assign-variables-in-a-function/34833/1 "2020-02-18T21:48:31Z")

</div>

I would like to assign variables in functions. For example,

```julia
function func(p)
a = A(p)
b = B(p)
c = C(p)
# Then do something using a, b, c
end

```

Those `a, b, c` are parameters I want to use in the function, and they depend on another parameter `p`.  
The same parameters are used in several functions, and I don’t want to repeat the same assignment in all the functions.  
It seems that I can use a macro with `esc()` to replace the assignment statement, but is therer a better way to do this?

Thank you.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 18, 2020, 10:04pm UTC](https://discourse.julialang.org/t/dynamically-assign-variables-in-a-function/34833/2 "2020-02-18T22:04:32Z")

</div>

> [@linwaytin](#):
>
> The same parameters are used in several functions, and I don’t want to repeat the same assignment in all the functions.

If you need to repeat several calculations like this in a bunch of places, then you should refactor it as a function:

```julia
a,b,c = ABC(p)

```

If you want to perform the calculation once and then re-use the _values_ `a,b,c` in many functions, then you should pass them as parameters to those functions. If you are always passing `a,b,c` together, that might be a hint that you should collect them into `struct` or some other data structure.

---

<div class="post-metadata">

**Author:** ![linwaytin](https://avatars.discourse-cdn.com/v4/letter/l/898d66/32.png) [@linwaytin](https://discourse.julialang.org/u/linwaytin)\
**Post date:** [February 18, 2020, 10:19pm UTC](https://discourse.julialang.org/t/dynamically-assign-variables-in-a-function/34833/3 "2020-02-18T22:19:31Z")

</div>

I need to recalculate them according to `p`.  
Thanks for your suggestions.
