# Function specialization in Printf

**URL:** <https://discourse.julialang.org/t/function-specialization-in-printf/108611>\
**Category:** General Usage\
**Created:** [January 10, 2024, 9:05am UTC](https://discourse.julialang.org/t/function-specialization-in-printf/108611 "2024-01-10T09:05:19Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![jsjie](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jsjie/32/22477_2.png) [@jsjie](https://discourse.julialang.org/u/jsjie)\
**Post date:** [January 11, 2024, 2:15am UTC](https://discourse.julialang.org/t/function-specialization-in-printf/108611/3 "2024-01-11T02:15:09Z")

</div>

I modified the code according to the referencence like the following:

```julia
function my_printf!(io, format::Printf.Format, args::Vararg{Any, N}) where {N} = tuple(args...)
    pos = Printf.format(LOG_DATA_BUFFER, 1, format, args...)
    GC.@preserve LOG_DATA_BUFFER unsafe_write(io, pointer(LOG_DATA_BUFFER), pos - 1)
    return
end

```

But this does not compile:

```julia
ERROR: LoadError: syntax: unexpected "="

```

where did I do wrong?

ps: I’ve somehow succeed by another way: declaring the `my_printf!` with `@inline`. Most of the allocations have been removed, I’ll dig further for the remainings.

* * *

I’ve found two things.  
First, `@inline` is a hint to compiler, but it will not force the compiler to do so. I didn’t find a way to do so, and for an example complicated as this one, it will be hard to follow the ideas in [this post](https://discourse.julialang.org/t/forcing-inline/20225/2) to make it concrete. My temporary solution is to split the long `printf` into several short ones, so that they will be inlined.

Second, I’ve used this way in my code:

```julia
const FORMAT_STH = Printf.Format(format_string)
function do_sth()
    my_printf!(io, FORMAT_STH, someargs)
end

```

I suppose in this way, it will all be compiled. However, when there are both `%s` and `%d` in the `format_string`, it will not be specialized. The compiled binary will need to compile the whole `my_printf!` for this case. Again, my temporary solution is to split the `printf` into several shorter ones, each containing `%s` or `%d` only.

---

_[View the full topic](https://discourse.julialang.org/t/function-specialization-in-printf/108611)._
