f(s::String) 和 f(::String) 的区别

mih*_*mek 3 syntax julia

以下两个函数有什么区别?

julia> one(s::String) = return 1
one (generic function with 1 method)

julia> one(::String) = return 1
one (generic function with 1 method)
Run Code Online (Sandbox Code Playgroud)

两者似乎都被允许,它们之间似乎没有区别。我想不包括v可能向编译器发出未使用参数值的信号,但是这又是编译器可以弄清楚的,对吧?(免责声明:我不知道编译器是如何工作的)

phi*_*ler 6

如果不使用参数没有区别,是的,对于编译器来说,这应该是微不足道的。

不过,您可以将其_用作实际的“丢弃参数”,解析器将阻止您使用它:

julia> f(_) = _ + 1
ERROR: syntax: all-underscore identifier used as rvalue around REPL[9]:1
Run Code Online (Sandbox Code Playgroud)

这在某些情况下很有用:

julia> _, _, z = (1,2,3)
(1, 2, 3)

julia> z
3

julia> _
ERROR: all-underscore identifier used as rvalue
Run Code Online (Sandbox Code Playgroud)

尽管

julia> x, x, z = (1,2,3)
(1, 2, 3)

julia> x
2
Run Code Online (Sandbox Code Playgroud)

有点混乱。


更多技术

但是,IR 中保留了一个未使用的参数:

julia> one(::String) = return 1
one (generic function with 1 method)

julia> one2(s::String) = return 1
one2 (generic function with 1 method)

julia> ir = @code_lowered one("sdf")
CodeInfo(
1 ?     return 1
)

julia> ir.slotnames
2-element Array{Symbol,1}:
 Symbol("#self#")  
 Symbol("#unused#")

julia> ir2 = @code_lowered one2("sdf")
CodeInfo(
1 ?     return 1
)

julia> ir2.slotnames
2-element Array{Symbol,1}:
 Symbol("#self#")
 :s 
Run Code Online (Sandbox Code Playgroud)

如果您关心插槽名称。我无法想象这将如何改变进一步的编译,但它可能是元编程中的一个极端情况。