Julia doc 关于 @generated:
A very special macro is @generated, which allows you to define so-called generated functions. These have the capability to generate specialized code depending on the types of their arguments with more flexibility and/or less code than what can be achieved with multiple dispatch. While macros work with expressions at parsing-time and cannot access the types of their inputs, a generated function gets expanded at a time when the types of the arguments are known, but the function is not yet compiled.
方便吧!
@generated function bar(x) # 没有@generated会报错
if x <: Integer
return :(x^2) # 注意,:表示quoted expression,不能少!
elseif x<:AbstractString
return :(string(x,", hello world!")) # 注意,不能少“:”
else
return :(x*3) # 注意,不能少“:”
end
end
有趣吧!
dat1 =bar(5.0) # 15.0
dat2 =bar(5) # 25
dat3 =bar("wo")# wo,hello world