Running Go Programs
Building and Running Go Code
To run Go code, you need to do the following:
- Download Go from https://golang.org/
- Create a source code directory and input your Go code in there, with extension
.go
- Ways to run code
- Running one Go file: two ways
- Use
go build <filename>
then run./<filename>
to run Go executable - Use
go run <filename>
to build and run code in one command
- Use
- Running a Go source directory
- Be in the directory one above the Go source directory
- Run
go build -o <output-executable> <source-directory>
, in which<output-exectuable>
is your custom name of the Go executable - Run
./<output-executable> <args>
, in which<args>
are potential input arguments to executable
- Running one Go file: two ways
Hello World
Sample code link: (https://repl.it/@jjoco/go-hello-world)
To create a "Hello World" program, you need a main function, like other C-like languages. Take the following example:
1 2 3 4 5 6 7 |
|
Notes
- The first statement in a Go source file must be package name. Executable commands must always use package main.
- Use
fmt
package in order to print out strings to the console. Here are some important functions:fmt.Println(... args)
: prints a list of variables to STDOUT with default formatting and inserts spaces between the variables and appends a new line at the end.fmt.Printf(stringFormat, fields)
: allows you to specify the formatting using a format template