Go Lang - Basic Syntax
Introduction to Basic Syntax of Go
This guide provides an overview of the basic syntax of the Go programming language, including variables, data types, control structures, and functions.
Key Points:
- Go is a statically-typed language with a syntax that emphasizes simplicity and readability.
- Understanding basic syntax elements such as variables, constants, loops, conditionals, and functions is crucial for Go development.
- Go uses packages for modularity and has built-in support for concurrent programming with goroutines and channels.
Variables and Constants
In Go, variables are declared using the var
keyword, and constants are declared using the const
keyword.
// Example: Variable and constant declarations
package main
import "fmt"
func main() {
var message string = "Hello, World!"
const pi float64 = 3.14159
fmt.Println(message)
fmt.Println("Value of pi:", pi)
}
Control Structures
Go supports traditional control structures like if
, for
, and switch
.
// Example: Control structures in Go
package main
import "fmt"
func main() {
// Example: if statement
age := 25
if age >= 18 {
fmt.Println("Adult")
}
// Example: for loop
for i := 1; i <= 5; i++ {
fmt.Println("Iteration", i)
}
// Example: switch statement
fruit := "apple"
switch fruit {
case "apple":
fmt.Println("It's an apple")
default:
fmt.Println("Unknown fruit")
}
}
Functions
Functions in Go are defined using the func
keyword and can accept multiple parameters and return multiple values.
// Example: Functions in Go
package main
import "fmt"
func main() {
result := add(5, 3)
fmt.Println("Sum:", result)
}
func add(a, b int) int {
return a + b
}
Summary
This guide provided an overview of the basic syntax of Go, covering variables, constants, control structures, and functions. By understanding these fundamental concepts, you can start writing and understanding Go programs effectively.