Crystal - 方法指针
Crystal - method pointers
是否可以在 Crystal 中使用方法指针?
如果是,我该如何创建和使用它们?
我希望将多条指令存储在一个数组中,然后稍后在程序中调用所需的指令。
这就是 Proc
的用途。
def foo()
puts "foo"
end
def bar()
puts "bar"
end
procs = {->foo, ->bar}
procs.each do |p|
p.call
end
产出
foo
bar
在线查看:https://play.crystal-lang.org/#/r/2vb7
它也适用于方法和静态方法:
class A
def self.foo()
puts "A.foo"
end
def bar()
puts "bar"
end
end
proc = ->A.foo
puts proc
proc.call
a = A.new
proc = ->a.bar
proc.call
在官方文档中阅读更多内容:https://crystal-lang.org/docs/syntax_and_semantics/literals/proc.html
是否可以在 Crystal 中使用方法指针?
如果是,我该如何创建和使用它们?
我希望将多条指令存储在一个数组中,然后稍后在程序中调用所需的指令。
这就是 Proc
的用途。
def foo()
puts "foo"
end
def bar()
puts "bar"
end
procs = {->foo, ->bar}
procs.each do |p|
p.call
end
产出
foo
bar
在线查看:https://play.crystal-lang.org/#/r/2vb7
它也适用于方法和静态方法:
class A
def self.foo()
puts "A.foo"
end
def bar()
puts "bar"
end
end
proc = ->A.foo
puts proc
proc.call
a = A.new
proc = ->a.bar
proc.call
在官方文档中阅读更多内容:https://crystal-lang.org/docs/syntax_and_semantics/literals/proc.html