For example there is a -c
option in Ruby that checks syntax before running a code:
C:\>ruby --help
Usage: ruby [switches] [--] [programfile] [arguments]
-c check syntax only
C:\>ruby -c C:\foo\ruby\my_source_code.rb
Syntax OK
Is there a similar functionality in Go?
P.S. An example from Ruby is only because I know it in Ruby. Not because of trolling or something.
golang syntax checker
Place the below code in a file called gochk in a bin dir and
chmod 0755
.Then run
gochk -- help
Is there much point only checking the syntax? The Go compiler is so fast you might as well compile everything too.
In this sense, the underlying mental model is quite different from that of Ruby.
Just use
go build
orgo install
. http://golang.org/cmd/go/Updated answer for those that don't want to settle for only checking with
gofmt
:You can substitute
gotype
forgo build
to get just the front-end of the go compiler that validates both syntax and structure: https://godoc.org/golang.org/x/tools/cmd/gotypeIt's comparative in speed to
gofmt
, but returns all the errors you'd get fromgo build
.The one caveat is that it appears to require other packages to be
go install
ed, otherwise it doesn't find them. Not sure why this is.You can use
gofmt
to check for syntax errors without actually building the project.You can later use $? bash variable, return code 0 implies success, 2 means syntax check. /dev/null will eat the code, but the errors go to stderr
The
-e
option is defined as:In agreement with @Rick-777, I would strongly recommend using
go build
. It performs additional checks thatgo fmt
does not (ex: missing or unnecessary imports).If you are worried about creating a binary in your source directory, you could always
go build -o /dev/null
to discard the output, which essentially reducesgo build
to a test that the code will build. That gets you syntax checking, among other things.EDIT: note that
go build
doesn't generate a binary when building non-main packages, so you don't need the -o option.Ruby is an interpreted language so a command that checks the syntax might make sense (since I assume you could potentially run the program even if there are syntax errors at some point).
Go on the other hand is a compiled language so it cannot be run at all if there are syntax errors. As such, the simplest way to know if there are errors is to build the program with
go build
.