OCaml for Go developers
UPDATE: There is a lot of work happening right now that should make these things easier and more convenient. By the time you read this, it might already be outdated. Please check here to see the most up-to-date information.
This post should serve as an introduction and a reference for people new to the OCaml ecosystem, but are experienced in Go tooling.
Starting a new project
Note: go doesn’t create a new directory, but dune always creates a new directory unless you specify the directory.
go mod init github.com/<username>/<modname>
# Creates a new directory named "proj_name"
dune init proj proj_name
# Creates a new project in the current directory
dune init proj proj_name .
Then:
cd
to the project directory.- Run
opam swich create .
to create a new sandbox for your dependencies. Think venv in python. - Run
eval $(opam env)
.
Building your code
go build .
dune build
Running your app
go run .
dune exec proj_name.exe
Formatting your code
In both ecosystems formatting is usually done by the respective editor/plugin combination. Below are the steps of how to manully format the entire codebase. In OCaml you need to install the formatter separately and setup formatting once. (Although there is ongoing work to fix that)
gofmt -w .
# one time setup
opam install ocamlformat
echo $(ocamlformat --version) > .ocamlformat
# every time after that
dune fmt
Adding a dependency
go get <dependency>
opam install <dependency>
In OCaml we’re not done yet:
- Open
dune-project
and add the dependency along with its version constraint to the dependency list.
(package
(name proj_name)
(synopsis "My very cool project")
(description "A longer description")
(depends
(<dependency> (= 1.2.3)))
(tags
()))
- Go to the file where you want to use this dependency.
- In that directory open the
dune
file. - Create a
libraries
stanza if one doesn’t exist. - Add the dependencies name to the
libraries
stanza, like so:
(library
(libraries dependency)
(name module_name))
Why do we need to all of that work?
Multiple reasons: The biggest is that OCaml is an old language and back then ease of use wasn't much of a concern. Another reason is that the dune build system is still rather young and currently, as the name implies, is only a build system. So we need to use opam, the OCaml package manager, to install the dependency and then tell our build system that we want to use the dependency.Actually the first step, adding to dune-project
, isn’t stricly necessary, but it’s good
practice and you will be thankful later if you are diligent and always add the dependency
to dune-project
as well.