简体   繁体   English

OCaml 模块中的私有值?

[英]Private values in OCaml module?

Is is possible to have a let binding (whether a function, value etc.) that is private to its module, and not visible from outside?是否有可能拥有一个对其模块私有且从外部不可见的let绑定(无论是函数、值等)吗?

Let's say we have A.ml :假设我们有A.ml

let exported = 1
let local = 2

I only want exported to be accessible from other modules.我只希望exported可以从其他模块访问。 B.ml : B.ml

let a = A.exported
let error = A.local (* This should error *)

Similar to what let%private does in Reason .类似于let%privateReason中所做的。

This is the motivation behind signature and mli files: they allow to hide information to the external world and expose only the relevant part of your API and not implementation details.这就是签名和 mli 文件背后的动机:它们允许向外部世界隐藏信息,并且只公开 API 的相关部分,而不是实现细节。 In your case, it would look like在你的情况下,它看起来像

(* A.ml *)
let exported = 1
let local = 2

and

(* A.mli *)
val exported: int

Then only exported will be visible outside of A.ml .然后只有exported的内容在A.ml之外可见。

Yes, that's what module signatures and on the file level the .mli file is for.是的,这就是模块签名.mli 文件在文件级别上的用途

Briefly explained, add an A.mli , then put the definitions you want to export into it:简单解释一下,添加一个A.mli ,然后将要导出的定义放入其中:

val exported : int

This isn't idiomatic, but for completion's sake:这不是惯用的,但为了完成:

Since 4.08 , when open was extended to accept arbitrary module expressions, it's possible to create private bindings without using module signatures:4.08开始,当open被扩展为接受任意模块表达式时,可以在不使用模块签名的情况下创建私有绑定:

open struct
  let local = 2
end

Before this you'd have to give the module a name and then open it, which will expose the module with its contents, although it can of course be given a name that suggests it shouldn't be used.在此之前,您必须为模块命名,然后打开它,这将公开模块及其内容,尽管它当然可以命名为暗示它不应该被使用。

module Internal = struct
  let local = 2
end

open Internal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM