Install and configure
Download at here then install.
Check version:
$ go version
go version go1.19.1 windows/amd64
Editor & organize source code
Visual Studio Code
Install the Go
plugin.
Hit Ctrl(Cmd)+Shift+P
, the VSCode command window opened. Click on Go: Install/Update Tools
. Select all the checkboxes showed up. Then click "OK".
GoLand
If you download the Go package after install GoLand, you have to configure GOROOT
:
Go to Settings (or Ctrl+Alt+S
) > Go > GOROOT > Download the Go SDK.
Configure GOPATH
Settings > Go > GOPATH
It defaults to a directory named go inside your home directory:
$HOME/go
on Unix$home/go
on Plan 9%USERPROFILE%\go
(usuallyC:\Users\YourName\go
) on Windows
Run kind
Click on Run bar > Edit configurations. At run kind, you can choose "File", "Directory" or "Package".
Go command
go mod init
Go module is a directory on hard drive that has a go.mod
file. That file contains some configuration information about the module itself.
$ go mod init github.com/huytunguyenn/webservices
The first argument is the name of the module itself. When using go get
command to retrieve dependencies, that information is used.
go get
To include a package, we import it and Go automatically downloads it when we build or run the project. Or we can download it manually using the go get
command.
$ go get github.com/huytunguyenn/webservices
import (
"github.com/huytunguyenn/webservices"
)
go run
Run a file:
$ go run main.go
You can also run by the name that initialized in go.mod:
$ go run github.com/huytunguyenn/webservices
$ go run .
go build
Create executable file.
Simple demo
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello world")
}
A package is a collection of files which declare constants, types, variables and functions belonging to the package.
Each source file begins with a package clause defining the package to which it belongs
=> Constants, types, variables and functions belonging to a package are accessible in all files of that package.
The package main
tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the main package is the entry point of the program.
fmt
stands for formatted I/O
Result:
GOPATH=C:\Users\HUYTU\go #gosetup
C:\DEV_PROGRAMS\Go\bin\go.exe build -o E:\TEMP\GoLand\___go_build_main_go.exe D:\Desktop\learn-go\main.go #gosetup
E:\TEMP\GoLand\___go_build_main_go.exe
Hello world
You can give aliases to package:
import (
"fmt"
str "strings"
)
langs := []string{"F#", "Go", "Python", "Perl", "Erlang"}
s := str.Join(langs, ", ")