In Golang, variables must be declared before use. You can use the var
keyword or the short variable declaration :=
for local variables.
package main
import "fmt"
func main() {
// Using var keyword
var num int = 10
var name string = "John"
// Short variable declaration
age := 25
fmt.Printf("Name: %s, Age: %d, Number: %d\n", name, age, num)
}
Golang has several basic data types, including integers (int
, int8
, int16
, etc.), floating - point numbers (float32
, float64
), booleans (bool
), and strings (string
).
Golang supports common control structures like if - else
, for
, and switch
.
package main
import "fmt"
func main() {
// if - else
num := 15
if num > 10 {
fmt.Println("Number is greater than 10")
} else {
fmt.Println("Number is less than or equal to 10")
}
// for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// switch
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
}
Functions in Golang are declared using the func
keyword. They can have zero or more parameters and zero or more return values.
package main
import "fmt"
// Function with two parameters and one return value
func add(a int, b int) int {
return a + b
}
func main() {
result := add(3, 5)
fmt.Println("Sum:", result)
}
One of the most powerful features of Golang is its built - in support for concurrency. Goroutines are lightweight threads of execution that can run concurrently. Channels are used to communicate between goroutines.
package main
import (
"fmt"
"time"
)
func printNumbers() {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(i)
}
}
func main() {
go printNumbers()
time.Sleep(1 * time.Second)
fmt.Println("Main function exiting")
}
To start using Golang, you need to install it on your system. You can download the official Go distribution from the
Go website
. After installation, you can verify it by running go version
in your terminal.
.go
extension, for example, hello.go
.package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
go run hello.go
in the terminal.If you want to build an executable file, you can use the go build
command. For example, go build hello.go
will create an executable file named hello
(or hello.exe
on Windows).
In Golang, errors are just values. Functions often return an error as the last return value. You should always check for errors in your code.
package main
import (
"fmt"
"strconv"
)
func main() {
numStr := "abc"
num, err := strconv.Atoi(numStr)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Number:", num)
}
}
Golang uses packages to organize code. You can use the go mod
command to manage dependencies. To initialize a new module, run go mod init <module - name>
in your project directory.
Golang has a built - in code formatter called gofmt
. You can run gofmt -w yourfile.go
to format your code according to the standard Go style.
Use comments to document your code. Golang also has a tool called godoc
that can generate documentation from your source code. You can write comments in a special format to make the documentation more informative.
// add is a function that takes two integers and returns their sum.
func add(a int, b int) int {
return a + b
}
Golang has a built - in testing framework. You can write test functions in files with names ending in _test.go
.
package main
import "testing"
func add(a int, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
Run the tests using the go test
command.
Golang is a powerful and versatile programming language with many unique features. Its simplicity, efficiency, and built - in support for concurrency make it a great choice for building modern applications. By understanding its fundamental concepts, usage methods, common practices, and best practices, you can start writing high - quality Go code. Whether you are building web applications, network services, or system tools, Golang has the capabilities to meet your needs.