Master Go Basics: From Variables to Concurrency in One Guide
This article provides a comprehensive, beginner‑friendly walkthrough of Go language fundamentals, covering variable and constant declarations, zero values, functions with multiple returns and variadic parameters, struct‑based OOP, non‑intrusive interfaces, slices, maps, goroutines, channels, and the simple error‑handling model with defer, panic, and recover.
Introduction
The article targets programmers familiar with other object‑oriented languages (Java, PHP) who are new to Go. It compares Go with Java to illustrate basic syntax, object‑oriented concepts, concurrency, and error handling.
Basic Syntax
Go (Golang) is a statically typed, compiled language created by Google. Its syntax resembles C, but it adds memory safety, garbage collection, and CSP‑style concurrency.
Variables, Constants, Nil and Zero Values
Variable declaration can use the var keyword (type follows the name) or the short form :=. Example:
var num int
var result string = "this is result"
num := 3 // equivalent to var num int = 3Constant declaration uses the const keyword. Example: const laugh string = "go" Nil and zero values : Uninitialized variables hold nil. Types receive default zero values (0 for numbers, false for booleans, empty string for strings).
Methods, Packages, and Visibility
Functions are defined with the func keyword. Packages determine visibility: an identifier is exported when its first letter is uppercase; otherwise it is private to the package.
// Hello World example
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
fmt.Println(add(3, 5)) // 8
}
func add(a int, b int) int {
return a + b
}Multiple Return Values and Variadic Parameters
Go functions can return multiple values, which is useful for error handling.
func add(a, b int) (int, error) {
if a < 0 || b < 0 {
return 0, errors.New("only non‑negative integers allowed")
}
return a + b, nil
}
func main() {
x, y := -1, 2
sum, err := add(x, y)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("add(%d, %d) = %d
", x, y, sum)
}Variadic functions accept an arbitrary number of arguments:
func myfunc(numbers ...int) {
for _, n := range numbers {
fmt.Println(n)
}
}
slice := []int{1,2,3,4,5}
myfunc(slice...)Pointers
Pointers hold memory addresses. The & operator obtains an address, and * dereferences it.
func main() {
i := 0
fmt.Println(&i) // e.g., 0xc00000c054
a, b := 3, 4
fmt.Println(add(&a, &b))
}
func add(a *int, b *int) int {
return *a + *b
}Arrays, Slices, and Maps
Arrays have fixed length. Example: var nums [3]int = [3]int{1,2,3} Slices are dynamic views over arrays. Length is len(s), capacity is cap(s). Creation examples:
var s []int = []int{0,1,2}
slice1 := nums[0:2] // {1,2}
slice2 := make([]int, 5) // length 5, capacity 5
slice3 := make([]int, 4, 5)Maps store key‑value pairs and are unordered. Declaration and usage:
m := map[string]int{"java":1, "go":2, "python":3}
m["go"] = 4
value, ok := m["java"]
if ok { fmt.Println(value) }
delete(m, "python")Object‑Oriented Programming with Structs
Go does not have classes; struct types serve a similar purpose.
type Student struct {
id int
name string
male bool
score float64
}
func NewStudent(id uint, name string, male bool, score float64) *Student {
return &Student{id, name, male, score}
}
func (s Student) GetName() string { return s.name }
func (s *Student) SetName(name string) { s.name = name }
student := NewStudent(1, "Alice", true, 95)
fmt.Println(student)Interfaces – Non‑Intrusive Design
In Go, a type implements an interface implicitly by providing all required methods. No explicit implements keyword is needed.
type IFile interface {
Read([]byte) (int, error)
Write([]byte) (int, error)
Seek(int64, int) (int64, error)
Close() error
}
type File struct{}
func (f *File) Read(b []byte) (int, error) { return 0, nil }
func (f *File) Write(b []byte) (int, error) { return 0, nil }
func (f *File) Seek(off int64, whence int) (int64, error) { return 0, nil }
func (f *File) Close() error { return nil }
// File satisfies IFile without any explicit declaration.Concurrency: Goroutine and Channel
Goroutines are lightweight threads started with the go keyword.
func say(s string) { fmt.Println(s) }
func main() {
go say("world")
say("hello")
}Channels enable communication between goroutines.
func sum(s []int, c chan int) {
total := 0
for _, v := range s { total += v }
c <- total
}
func main() {
data := []int{7,2,8,-9,4,0}
c := make(chan int)
go sum(data[:len(data)/2], c)
go sum(data[len(data)/2:], c)
x, y := <-c, <-c
fmt.Println(x, y, x+y)
}Error Handling
Go uses a simple error interface: type error interface { Error() string } Typical pattern:
result, err := Foo(param)
if err != nil {
// handle error
} else {
// use result
} deferguarantees execution of a statement when the surrounding function returns, similar to finally in Java.
func ReadFile(name string) ([]byte, error) {
f, err := os.Open(name)
if err != nil { return nil, err }
defer f.Close()
// read file …
return data, nil
} panicaborts 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
", r)
}
}()
i, j := 1, 0
_ = i / j // triggers panic
}
func main() {
divide()
fmt.Println("continue after panic")
}Conclusion
The guide gives a quick yet thorough overview of Go’s core features, enabling readers to write simple programs, understand Go’s type system, and start exploring its powerful concurrency model.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JD Retail Technology
Official platform of JD Retail Technology, delivering insightful R&D news and a deep look into the lives and work of technologists.
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.
