定义函数时不能用@printf怎么办

我这样定义了一个函数

format(fmt,num) = @printf(fmt,num)

竟然返回了这样一个错误

ERROR: LoadError: ArgumentError: @printf: first or second argument must be a format string
Stacktrace:
 [1] @printf(::LineNumberNode, ::Module, ::Symbol, ::Vararg{Any,N} where N) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.3/Printf/src/Printf.jl:41
in expression starting at REPL[39]:1

这样用的话还好好的

@printf "%2.2f" 3.1415

这是肿么回事

怀疑是宏在函数定义时就要展开,所以报错。

看 sf 的回答估计是做了 code gen 了。

workaround:

print_formatted(fmt, args...) = @eval @printf($fmt, $(args...))

@eval 速度缓慢警告 :warning:

也有包提供函数,肯定是比 @eval 快了

是只有这个宏有这种情况吗?我记得这个函数没问题

function bfsprint(graph::Graph{T},startindex::UInt64) where T
    vertex1 = vertexof(getadjlist(graph,startindex))
    vertex1.color=Black

    q=Queue{Vertex{T}}()
    push(q,vertex1)
    #adjlist has been changed!!
    while @lengthof(q) != 0
        v1=remove(q)
        print(valueof(v1))
        edge=edgeof(graph,indexof(v1))
        for (vertex,w) in edge
            if vertex.color != Black
                push(q,vertex)
                vertex.color=Black
    
            end
        end
    end
    
end

还是说只有当返回的语句用到宏代码时才会产生错误