Go Basic Syntax
Covers the basic syntax of the Go programming language.
Getting Started with Go
Go, also known as Golang, is a statically-typed, concurrent programming language developed by Google. It has a simple, expressive syntax that makes it easy to write efficient and readable code. In this article, we’ll take a closer look at the basic syntax, including how to declare variables, write functions and use control structures.
Variables
In Go, variables can be declared using the var
keyword, followed by the variable name and its type. For example:
var x int
You will notice, if you come from a language such as Java, C# or C++, there isn’t a semicolon at the end of the variable declaration. That is intended. If you put a semicolon there the compiler won’t like it. The reason for this is the compiler has a feature built-in that adds semicolons where and when needed so you as a developer don’t have to worry about whether or not you put one in the right location or to remember to put them. You can just write code and the compiler will do the rest.
Functions
Functions in Go are declared using the func
keyword, followed by the function name, its parameters, and its return type. For example:
func subtract(a int, b int) int {
return a - b
}
This declares a function named subtract with two parameters, a and b of type int, and then returns an int type.
Control Structures
Go has the basic control structures that you would expect from a programming language, including if
statements, which can also make use of else if
and else
clauses, and the switch
statement. For example:
package main
import "fmt"
func main() {
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
}
for i := 0; i < 5; i++ {
fmt.Println(i)
}
switch x {
case 10:
fmt.Println("x is 10")
default:
fmt.Println("x is not 10")
}
}
Conclusion
Go has a simple, expressive, syntax that makes it easy to write efficient and readable code. Whether you’re new to programming or an experience developer, Go is a language worth exploring. With its strong focus on concurrency and its efficient runtime. Go is ideal for building high-performance and scalable applications. Go out and get started with Go today!