After you install Go, we need to check to see if it is configured properly.
Things work better with a Go Path set. This is usually under your home directory. In Windows that would be C:\Users\<username>\go
most likely. You can check this by going to the command prompt and typing:
go env
This is going to do two things. Making sure you have go installed and the Go executable is in your path so you can work with it. And second, it is going to make sure you have the correct Go variables set.
If you don’t have gopath set, you can modify your environment by using the following command in Windows
setx GOPATH %USERPROFILE%\go
Make sure that folder exists, and you’ll be good, as long as everything else with the install when OK. If not, you may need to try the install again.
Writing the Code
We’re going to start with a basic, “Hello World” app, because of all of the reasons.
Here’s your code. Inside of Visual Studio Code, I’ve placed created a “Go” folder, and then a sub-folder for this project. I called it hello
, and the file I named hello.go
.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
So, what is it doing.
First, we define a package. A package is a way to group related functions together. The package does not have to be named the same as the file.
Next we import fmt
, and any other libraries we need. fmt
is a library which handles a lot of the input/output commands, similar to stdio.h in the C language.
Next we need to define our main function. Go uses main, similar to many other languages (Java, C/C++, etc). This makes sense as it was designed to be used by C++ and Java developers, who needed a better tool, so keeping thing similar helps.
You’ll notice to define your main function, you precede it with the func
keyword. (Because it saves so much time compared to writing function
like in JavaScript.)
To call the print function, we reference the library fmt, and then call it’s function, passing parameters as needed.
Compiling & Running
Next you need to get the file ready to compile/run. However, you need a go.mod
file to make this work. To create this, run the following command, from within the folder where your project is.
If you are in Visual Studio Code, you can go to the terminal window and enter the command there.
go mod init access2learn.com/hello
The initializes (creates) the mod file, specifying where it is from. Of course, you can use any domain name you want, I just chose mine. This is to reference the company that you are working for.
It is recommended that you run tidy after updating your project as it will clean up the mod file.
go mod tidy
You cannot compile and run your code without the go.mod file, so make sure you run this.
Once you have your mod file, you can then run your command.
go run .
This finds the file you want to use, based upon the mod.go file, and runs it, in this case displaying Hello World.
A First App in Go was originally found on Access 2 Learn
3 Comments
Comments are closed.