Open rodriggj opened 2 years ago
go to How to Write Go Code How to Write Go Code
Install the Go Module in Visual Studio Code
Now you need to create a Module
go mod init example.com/go-demo-1
TERM: In Go modules are elements of distribution and versioning
NOTE: Typically you want the name of the module to be the location on the internet where you will download the module. Since we don't have one yet, we'll use a generic example.com/go-demo-1
When you run the previous command, GO will create a go.mod file which you can see in the directory structure.
Within our project directory of we now need to create a GO Package, which is just a folder that contains GO code. You can name the folder what ever you like, in this example we will name the folder mascot.
mkdir mascot
Within the mascot folder create a file called mascot.go. This will trigger the GO Extension to kickoff and when it does it will find that it is missing a few controls.
cd mascot
touch mascot.go
At the bottom-right of the Visual Studio Code editor you should see a dialog box appear prompting for an installation of some additional packages.
An installation process will kick-off in the console and display output similar to the following when complete:
NOTE: The syntax for the function signature is, func to indicate a function, function name which is BestMascot(), and return value data type which is string.
cd ..
touch main.go
go run main.go
And you should see the return statement "Tut" like we programmed into our BestMascot() function.
If you wanted to import additional external packages into your main application you would follow a process similar to the following.
For example, if we wanted to import the "quote" package. This package is not installed in our local env so Visual Studio immediately indicates an "error" with the red-squiggly line
The go.sum package has now been downloaded to our local directory structure, and upon a "Save" of the file, the error goes away, along with an additional file "go.sum" added to your project.
We can add tests to our code functionality by entering a new file with our automated tests. Here within the mascot directory, add a new file and add test to the file name like so:
cd mascot
touch mascot_test.go
Now within the _mascottest.go file enter the following code:
VS Code has detected that this is a test file and has provided an option to run test or debug. Here we can simply click run test.
As expected the test failed, because we hardcoded "Tut" in our BestMascot() function and we were testing to see if the return value was "Go Gopher". The terminal output reflects the test failure.
Installation