`pub(self)` 可见性与没有 `pub` 属性有何不同?
How is `pub(self)` visibility different from no `pub` attribute?
我 see 函数的可见性可以在模块中声明为 pub(self)
。这与没有 pub
属性的私有函数有何不同?如果它们没有区别,为什么会存在这种语法?
RFC 1422 中引入了 pub(restricted)
语法。它引入了两种指定可见性的新方法:
pub(crate)
: 使项目对整个当前板条箱可见,但不超过。
pub(in path::to::module)
: 使项目对路径指定的模块树可见。
pub(self)
是pub(in self)
的语法糖,属于第二类:self
只是一个路径,如super
、::foo
、bar::baz
等等。这意味着,是的,pub(self)
使项目对当前模块树可见。
因此,pub(self)
等同于省略pub(self)
声明。这甚至说明 in the RFC:
As noted above, the definition means that pub(self) item
is the same as if one had written just item
.
RFC 还提到了支持的原因:
The main reason to support this level of generality (which is otherwise just "redundant syntax") is macros: one can write a macro that expands to pub($arg)
item, and a macro client can pass in self
as the $arg
to get the effect of a non-pub definition.
我 see 函数的可见性可以在模块中声明为 pub(self)
。这与没有 pub
属性的私有函数有何不同?如果它们没有区别,为什么会存在这种语法?
RFC 1422 中引入了 pub(restricted)
语法。它引入了两种指定可见性的新方法:
pub(crate)
: 使项目对整个当前板条箱可见,但不超过。pub(in path::to::module)
: 使项目对路径指定的模块树可见。
pub(self)
是pub(in self)
的语法糖,属于第二类:self
只是一个路径,如super
、::foo
、bar::baz
等等。这意味着,是的,pub(self)
使项目对当前模块树可见。
因此,pub(self)
等同于省略pub(self)
声明。这甚至说明 in the RFC:
As noted above, the definition means that
pub(self) item
is the same as if one had written justitem
.
RFC 还提到了支持的原因:
The main reason to support this level of generality (which is otherwise just "redundant syntax") is macros: one can write a macro that expands to
pub($arg)
item, and a macro client can pass inself
as the$arg
to get the effect of a non-pub definition.