This post is a continuation to my GoLang series. Today, we shall be looking at the basics of Go, its syntax and some few inbuilt functions and methods. Let's Go!
The Go syntax is fairly easy and straightforward when reading it. Let's take a look at it
Let us break down the syntax below:
1) package main
We start from the package level, were we declare the main package like so. All Go code are started with a package main declaration. Packages are kind of modules and they can only be instantiated once throughout the entire code. Any package declared in the package level gives a global scope and other part of the code have access to that package.
The import statement is used to import in-built packages as well as third party packages. "fmt" is Go's specially built in format tool that formats Go code as well as enforce some strict code convention in Go.
3) func main()
The third part of the source code as seen in the picture above, all our code is written in the main function, from were we can also run our code.
When we run the function using go run filename.go, the output is displayed in the terminal window. In our case when we type go run Example.go, the output is displayed in the terminal.
Now, lets look at how we can declare variables in Go, how they are initialized and how we can perform some operations on them
To declare variables in Go, it can be done in three ways. Lets take a look at them below.
1) var dev int
i = 42
Let's break down that above. First, we declare the variable using the var keyword along side the name of the variable, in this case we are using dev as the variable name. The int keyword specifies the data type which translates to an integer in this case.
2) var myNumber int = 100
Looking at the second declaration, we declare the variable name which is myNumber and also initialize it on the same line in which we set it to 100.
3) myString := "Hello Dev"
The third form of declaring variables is by typing the name of the variable on the left hand side, then using the := sets the variable and also initialize it. So, Go will know that 'myString' is a string because of the := symbol which sets a variable and also initialize it to what type of data type the variable is.
Variable Naming Convention
In Go, there are some naming conventions that must be followed.
1) All, variable names must start with a lowercase letter. Any variable that start with uppercase letter signifies to Go that such a variable wants to be exported and available globally.
There are four (4) major data types in Go which are listed below:
1) Basic Types: Numbers, Strings and Boolean
2) Aggregate Types: Array and Struct
3) Reference Types: Pointers, Slices, Map, Functions and Channels
4) Interface Type.
Above are the Data Types in Go. In the next post, we will look at them in details and how they can be implemented.
Feel free to leave a comment, and tell me what you think. Have a great weekend!
Top comments (0)