Welcome to the Go Syntax lesson! In this tutorial, we'll explore the fundamentals of Golang, a powerful, open-source programming language developed by Google. By the end of this lesson, you'll be well-equipped to write your own Go programs. š
Go, also known as Golang, is a modern, efficient, and easy-to-learn language. Its simplicity, combined with its powerful features, makes it an excellent choice for building large-scale applications, systems, and web services.
Before diving into Go syntax, let's first set up our development environment.
mkdir my_first_go_programcd my_first_go_programtouch main.goOpen main.go in your favorite text editor and paste the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}š” Pro Tip: Always start your Go files with the package main declaration. This indicates that the file is the main entry point for your application.
In Go, variables are declared without specifying their data type. Go infers the data type based on the value assigned to the variable.
var myVariable string = "Hello, World!"
fmt.Println(myVariable)Go constants are similar to variables but are declared with the const keyword. Constants are immutable and cannot be reassigned.
const Pi float64 = 3.14159
fmt.Println(Pi)Go functions are defined using the func keyword. The main() function is the entry point of every Go program.
func greet(name string) {
fmt.Println("Hello", name)
}
greet("John Doe")š” Pro Tip: In Go, functions can be passed as arguments to other functions, and they can also be returned from functions.
Go includes common control structures such as if, else, for, switch, and select.
if condition {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
for i := 0; i < 10; i++ {
fmt.Println(i)
}
switch expression {
case value1:
// code to execute if expression equals value1
case value2:
// code to execute if expression equals value2
default:
// code to execute if expression doesn't match any case
}Now that you've mastered the basics of Go syntax, it's time to put your knowledge into practice.
error type and the defer statement.Which keyword is used to declare a variable in Go?
Happy coding! š