未知类型的方法参数

Method argument of an unknown type

我正在尝试编写一个实用程序库,它试图在任意对象类型上调用方法。在 ruby 中,我会做类似的事情:

def foo(object)
  object.public_send(:bar)
rescue NoMethodError
  raise "Method not defined on object"
end

foo(instance_of_my_arbitrary_class)

我不确定如何在 Crystal 中执行此操作,因为类型未知,所以我收到 Can't infer the type of instance variable 'object'.

的编译器错误

如何在不知道将传递的对象类型的情况下完成此操作?

我想我是在利用一个模块并包含它之后才弄明白的。

module ArbitraryObject; end

class Arbitrary
  include ArbitraryObject
end

class MyLib
  def foo(object : ArbitraryObject)
    ... Code here ...
  end
end

MyLib.new(Arbitrary.new).foo

在Crystal中,您不能在任意对象上调用任意方法,因为方法是在编译时解析的,而不是运行时。如果用户试图将你的库方法与不兼容的类型一起使用,他将得到一个编译时错误:

def foo(object)
  object.bar
end

class MyObj
  def bar
    puts "bar!"
  end
end

foo(MyObj.new) # => "bar!"

这里有效,因为 MyObj 的实例具有方法 bar。但是如果你使用没有那个方法的东西,用户会得到一个编译时错误:

foo(3) # compile error: undefined method 'bar' for Int32

此错误将在程序执行前显示。