Go Language Basics: Syntax, Variables, Control Flow, OOP, Concurrency, and Error Handling
This article introduces Go to developers familiar with other object‑oriented languages, covering the language definition, basic syntax such as variable and constant declarations, control structures, functions with multiple returns and variadic parameters, data structures like arrays, slices and maps, struct‑based object‑orientation, interfaces, goroutine‑based concurrency, channels, mutexes, and the simple error‑handling model using error, defer, panic, and recover.
Introduction
The article is aimed at readers who have experience with Java or PHP but are new to Go, comparing Go features with Java and explaining core concepts to quickly get up to speed.
Go Definition
Go (Golang) is a statically typed, compiled language created by Google. Its syntax resembles C, but it adds memory safety, garbage collection, structural typing, and CSP‑style concurrency.
Basic Syntax
Variable declaration can be done with the var keyword (type after the name) or the short := form which infers the type from the right‑hand side.
var num int
var result string = "this is result"
num := 3Constant declaration uses the const keyword; constants cannot be changed after definition.
const laugh string = "go"Uninitialized variables have the zero value ( 0 for numbers, false for booleans, "" for strings, nil for pointers, slices, maps, etc.).
Functions
Functions are defined with func . Go supports multiple return values, which are useful for returning a result and an error.
func add(a int, b int) (int, error) {
if a < 0 || b < 0 {
return 0, errors.New("only non‑negative integers allowed")
}
return a + b, nil
}Variadic functions use ... to accept a variable number of arguments.
func myfunc(numbers ...int) {
for _, n := range numbers {
fmt.Println(n)
}
}Control Flow
Go’s if , for , and switch statements work similarly to Java, with for serving as the only loop construct (including traditional, condition‑only, and range loops).
if condition {
// ...
}
for i := 1; i <= 100; i++ {
sum += i
}
switch score {
case 90, 100:
fmt.Println("Grade: A")
default:
fmt.Println("Grade: F")
}Data Structures
Arrays have fixed length; slices provide dynamic, resizable views over arrays. Length is obtained with len(s) , capacity with cap(s) . Slices are created via literals, slicing an existing array, or using make .
var nums = []int{1, 2, 3}
var slice = nums[0:2] // {1,2}
slice2 := make([]int, 5, 10)Maps (dictionaries) store key‑value pairs and are created with literals or make .
m := map[string]int{"java": 1, "go": 2}
value, ok := m["java"]
if ok { fmt.Println(value) }Object‑Oriented Features
Go does not have classes; it uses struct types to define data structures. Methods are defined with a receiver argument.
type Student struct {
id int
name string
male bool
score float64
}
func (s Student) GetName() string { return s.name }
func (s *Student) SetName(name string) { s.name = name }Interfaces are satisfied implicitly: any type that implements the required methods satisfies the interface.
type Reader interface { Read(p []byte) (n int, err error) }
type File struct {}
func (f *File) Read(p []byte) (int, error) { /* ... */ }
// File now implements Reader without an explicit declaration.Concurrency
Goroutines are lightweight threads started with the go keyword.
func say(s string) { fmt.Println(s) }
func main() {
go say("world")
say("hello")
}Channels provide safe communication between goroutines.
ch := make(chan int)
ch <- 5 // send
v := <-ch // receiveSynchronization can be achieved with sync.Mutex .
type SafeCounter struct {
v map[string]int
mux sync.Mutex
}
func (c *SafeCounter) Inc(key string) {
c.mux.Lock()
c.v[key]++
c.mux.Unlock()
}Error Handling
Go uses a simple error interface. Functions return an error value as the last return parameter.
func Foo(param int) (int, error) { /* ... */ }
if n, err := Foo(0); err != nil {
// handle error
} else {
fmt.Println(n)
}The defer statement schedules a function call to run after the surrounding function returns, useful for resource cleanup.
func ReadFile(name string) ([]byte, error) {
f, err := os.Open(name)
if err != nil { return nil, err }
defer f.Close()
// read file
}panic aborts the current goroutine; recover (used inside a deferred function) can catch a panic and prevent the program from crashing.
func divide() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered: %v\n", r)
}
}()
i, j := 1, 0
_ = i / j // triggers panic
}Conclusion
The article provides a concise overview of Go’s core syntax, data structures, object‑oriented patterns, concurrency primitives, and error‑handling mechanisms, giving readers a solid foundation to start writing Go programs.
JD Tech
Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.