Master Go Basics: From Variables to Concurrency in One Guide
This article introduces Go language fundamentals for developers familiar with other object‑oriented languages, covering variable and constant declarations, zero values, methods, structs, interfaces, slices, maps, goroutines, channels, mutexes, and error handling with clear code examples and explanations.
Introduction
Go (also called Golang) is a statically typed, compiled language created by Google. It combines C‑like syntax with memory safety, garbage collection, and CSP‑style concurrency.
Basic Syntax
The language differs from Java in variable declaration, array, slice, and map usage, but the core concepts are similar.
Variables, Constants, Nil and Zero Values
Variables can be declared with the var keyword (type follows the name) or with the short form :=. Examples:
var num int
var result string = "this is result"
num := 3 // equivalent to var num int = 3Constants are declared with const and cannot be changed after definition: const laugh string = "go" Uninitialized variables have the value nil (similar to Java’s null) or a zero value: 0 for numbers, false for booleans, and "" for strings.
Methods and Packages
Methods are defined with the func keyword. Visibility is controlled by the first letter of the identifier: uppercase means exported (package‑level visible), lowercase means private.
func MethodName(p1 Param, p2 Param) int { }
// Hello World example
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
fmt.Println(add(3, 5))
}
func add(a int, b int) int {
return a + b
}Multiple Return Values and Variadic Functions
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
}Variadic parameters are declared with ...:
func myfunc(numbers ...int) {
for _, n := range numbers {
fmt.Println(n)
}
}
slice := []int{1,2,3,4,5}
myfunc(slice...)Slices, Arrays and Maps
Arrays have fixed length; slices provide a dynamic view over an underlying array. Length is obtained with len(s), capacity with cap(s). Slices are created by slicing an array or with make:
var nums = [3]int{1,2,3}
slice1 := nums[0:2] // {1,2}
slice2 := make([]int, 5) // length 5, capacity 5Maps store key‑value pairs and are declared like:
maps := map[string]int{"java":1, "go":2, "python":3}
maps["go"] = 4
value, ok := maps["one"]
if ok { /* use value */ }
delete(maps, "four")Object‑Oriented Concepts
Structs and Methods
Go does not have explicit classes; struct types serve that purpose. Example:
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 }Interfaces
Interfaces are satisfied implicitly: a type implements an interface by providing all its methods. Example of a non‑intrusive interface:
type IFile interface {
Read(buf []byte) (n int, err error)
Write(buf []byte) (n int, err error)
Seek(off int64, whence int) (pos int64, err error)
Close() error
}
type File struct { /* ... */ }
func (f *File) Read(buf []byte) (int, error) { /* ... */ }
func (f *File) Write(buf []byte) (int, error) { /* ... */ }
func (f *File) Seek(off int64, whence int) (int64, error) { /* ... */ }
func (f *File) Close() error { /* ... */ }Concurrency
Goroutine
Goroutines are lightweight threads started with the go keyword:
func say(s string) { fmt.Println(s) }
func main() {
go say("world")
say("hello")
}Channel
Channels enable communication between goroutines:
ch := make(chan int)
ch <- v // send
v := <-ch // receive func sum(s []int, c chan int) {
total := 0
for _, v := range s { total += v }
c <- total
}
func main() {
s := []int{7,2,8,-9,4,0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c
fmt.Println(x, y, x+y)
}Mutex
Synchronization 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
error Interface
The built‑in error interface defines a single method Error() string. Functions typically return a value and an error:
func Foo(param int) (int, error) { /* ... */ }
n, err := Foo(0)
if err != nil {
// handle error
} else {
// use n
}defer
deferschedules a function to run after 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 …
}panic and recover
panicaborts the current goroutine; recover can catch a panic when called inside a deferred function:
func divide() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Runtime panic caught: %v
", r)
}
}()
i, j := 1, 0
k := i / j // triggers panic
fmt.Printf("%d / %d = %d
", i, j, k)
}
func main() {
divide()
fmt.Println("divide returned, back in main")
}Conclusion
The article provides a quick start for developers transitioning to Go, covering syntax, data structures, OOP concepts, concurrency primitives, and error handling. Further study is recommended for advanced topics such as goroutine scheduling and performance tuning.
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 Cloud Developers
JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.
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.
