# Type functions in structs

**URL:** <https://discourse.julialang.org/t/type-functions-in-structs/105864>\
**Category:** General Usage\
**Created:** [November 6, 2023, 2:59pm UTC](https://discourse.julialang.org/t/type-functions-in-structs/105864 "2023-11-06T14:59:39Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![atteson](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@atteson](https://discourse.julialang.org/u/atteson)\
**Post date:** [November 6, 2023, 2:59pm UTC](https://discourse.julialang.org/t/type-functions-in-structs/105864/1 "2023-11-06T14:59:39Z")

</div>

Is there a way to implement the following without error:

```julia
B2I(T) = T == Bool ? Int : T

struct S{T}
  x::B2I(T)
end

s1 = S{Bool}( 3 )

```

---

<div class="post-metadata">

**Author:** ![Salmon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/salmon/32/22968_2.png) [@Salmon](https://discourse.julialang.org/u/Salmon)\
**Post date:** [November 6, 2023, 3:22pm UTC](https://discourse.julialang.org/t/type-functions-in-structs/105864/2 "2023-11-06T15:22:29Z")

</div>

Cannot check if its fully correct right now but something like this should work I think

```julia
B2I(T) = T == Bool ? Int : T

struct S{T}
  x::T
  function S{T} (x) where T
     new{B2I(T)}(x)
end

s1 = S{Bool}( 3 )

```

In essence, you just use a normal definition of the struct with a new constructor that makes sure the type is converted correctly.

---

<div class="post-metadata">

**Author:** ![atteson](https://avatars.discourse-cdn.com/v4/letter/a/91b2a8/32.png) [@atteson](https://discourse.julialang.org/u/atteson)\
**Post date:** [November 6, 2023, 3:47pm UTC](https://discourse.julialang.org/t/type-functions-in-structs/105864/3 "2023-11-06T15:47:24Z")

</div>

> [@Salmon](#):
>
> ```julia
> B2I(T) = T == Bool ? Int : T
> 
> struct S{T}
> x::T
> function S{T} (x) where T
> new{B2I(T)}(x)
> end
> 
> s1 = S{Bool}( 3 )
> 
> ```

That works. However, the point was to try to retain the fact that we want to view this as a Bool. I suppose I could store the type in a member but that feels inefficient.

---

<div class="post-metadata">

**Author:** ![Salmon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/salmon/32/22968_2.png) [@Salmon](https://discourse.julialang.org/u/Salmon)\
**Post date:** [November 6, 2023, 4:08pm UTC](https://discourse.julialang.org/t/type-functions-in-structs/105864/4 "2023-11-06T16:08:22Z")

</div>

Ah, would it be fine if your struct has two type parameters, (the first being Book). Otherwise, I’m not sure if it’s possible.  
Afaik one has to store the type of the variables in the parametric struct at least (otherwise the function B2I would have to be called each time something is inferred I guess).
