Julia中如何同时保留结构体构造函数与调用运算符的文档字符串?
问题描述
我编写了如下Julia模块:
module Foo export Bar """ Bar Struct bar docstring. """ struct Bar n::Int @doc """ Bar(n::Int) Constructor docstring. """ function Bar(n::Int) return new(n) end end end
在REPL中查询Bar的文档时,能同时看到结构体自身和构造函数的文档字符串。
但添加调用运算符重载代码后:
""" (b::Bar)(x::Int) Do something. """ function (b::Bar)(x::Int) return b.n + x end
执行using Foo时会出现警告:Replacing docs for Foo.Bar :: Tuple{Int64} in module Foo,此时构造函数的文档字符串会被调用运算符的文档字符串替换。
请问如何才能同时保留这两份文档字符串?
解决方法
核心原因:Julia的文档系统会把Bar(n::Int)(构造函数)和(b::Bar)(x::Int)(调用运算符)的方法签名都关联到Bar这个绑定上,导致新文档覆盖旧文档。以下是几种可行的解决方式:
方式一:为调用运算符文档指定明确目标
使用@doc宏显式指定文档的绑定目标,避免覆盖构造函数的文档。修改调用运算符的代码如下:
@doc """ (b::Bar)(x::Int) Do something. """ (::typeof((::Bar)(::Int))) function (b::Bar)(x::Int) return b.n + x end
或者更简洁的写法,直接将文档绑定到方法的类型签名:
@doc """ (b::Bar)(x::Int) Do something. """ (Bar, Tuple{Bar, Int}) function (b::Bar)(x::Int) return b.n + x end
方式二:合并构造函数文档到结构体主文档
把构造函数的说明直接整合到结构体的文档字符串中,这样即使调用运算符的文档被关联,构造函数的内容依然保留在结构体文档里:
""" Bar Struct bar docstring. # 构造函数 Bar(n::Int) Constructor docstring. """ struct Bar n::Int function Bar(n::Int) return new(n) end end
这种方式下,查询Bar时会看到结构体和构造函数的文档,查询(b::Bar)(x::Int)时会看到单独的调用运算符文档,互不干扰。
方式三:使用文档合并选项(Julia 1.6+)
在Julia 1.6及以上版本中,@doc宏支持merge=true选项,允许将新文档与已有文档合并而非替换:
@doc merge=true """ (b::Bar)(x::Int) Do something. """ function (b::Bar)(x::Int) return b.n + x end
添加该选项后,构造函数和调用运算符的文档会同时保留在Bar的文档中。
内容的提问来源于stack exchange,提问作者Fernando
相关产品推荐
相关产品推荐

