在晶体 0.21.1 中使用"macro inherited"定义实例方法



据我了解,类型声明的工作方式类似于kind_of...

"所以类型并不是严格意义上命名的类型,而是像is_a?kind_of? https://github.com/crystal-lang/crystal/issues/4232 一样。

所以我认为这段代码的一部分有效。

但是,当我使用宏在继承的类上定义实例方法时,错误消息会抱怨错误对象中缺少该方法。

class Base
  macro inherited
    def name
      "Joe Smith"
    end
  end
end
class Context < Base; end
class Render
  def initialize(@inner_context : Base); end
  def display
    name
  end
  forward_missing_to inner_context
  private property inner_context
end
puts Render.new(Context.new).display

输出为:

Error in line 23: instantiating 'Render#display()'
in line 15: instantiating 'name()'
in macro 'forward_missing_to' /usr/lib/crystal/object.cr:1132, line 1:
>  1.     macro method_missing(call)
   2.       inner_context.{{call}}
   3.     end
   4.   
expanding macro
in macro 'method_missing' expanded macro: forward_missing_to:1, line 1:
>  1.       inner_context.name
   2.     
undefined method 'name' for Base (compile-time type is Base+)

我在这里错过了什么?

@inner_context可以是类型 Base它没有定义base方法。

一种解决方案是将Base标记为抽象:abstract class Base

最新更新