Master Go Functions, Closures, Methods, and Interfaces: A Hands‑On Guide

This article explains Go's function syntax, parameter rules, multiple return values, closures, method definitions with value and pointer receivers, and interface implementation, providing clear code examples and output illustrations to help developers deepen their backend programming skills.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Go Functions, Closures, Methods, and Interfaces: A Hands‑On Guide

Function (function)

Functions can have no parameters or multiple parameters.

If consecutive named parameters share the same type, all but the last type can be omitted.

A name starting with an uppercase letter makes the function exported.

Functions can return any number of values.

Return values can be named, acting as variables defined at the top of the function.

Functions are values and can be used as parameters or return values.

func add(x, y int) int {
    return x + y
}
func swap(x, y string) (string, string) {
    return y, x
}
func division(dividend, divisor int) (quotient, remainder int) {
    quotient = dividend / divisior
    remainder = dividend - quotient * divisor
    return
}
// conpute accepts a function as a parameter
func conpute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

Function Closure (closure)

A closure stores a function together with its surrounding environment.

The environment captures external variables that the inner function can access and modify.

Closures are typically created by returning an inner function from an outer function.

If the outer function's variables have local lifetime, the closure's environment is closed; otherwise, global variables can affect the closure.

package main

import "fmt"

func test_1(x int) func() {
    return func() {
        x++
        fmt.Println(x)
    }
}

func test_2(x int) func() {
    sum := 0
    return func() {
        sum += x
        fmt.Println(x, sum)
    }
}

func test_3(x int) func(int) int {
    sum := 0
    return func(y int) int {
        sum += x * y
        return sum
    }
}

func main() {
    test_1(1)()
    test_2(1)()
    // each closure has a different external environment
    for i := 0; i < 5; i++ {
        fmt.Printf("%d ", test_3(1)(i))
    }
    fmt.Println()
    // each closure shares the same external environment (tmp)
    tmp := test_3(1)
    for i := 0; i < 5; i++ {
        fmt.Printf("%d ", tmp(i))
    }
    fmt.Println()
}

Program output:

2
1 1
1 1
0 1 2 3 4 
0 1 3 6 10

Method (method)

Go has no classes, but you can define methods on struct types. A method is a function with a special receiver parameter placed between the func keyword and the method name.

type Vertex struct {
    X, Y float64
}

func (v Vertex) distance() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Only methods with a pointer receiver can modify the receiver's underlying value.

If a method has a non‑pointer receiver, it receives a copy of the value.

A method with a pointer receiver can be called on both a pointer and a value; the compiler takes the address automatically.

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Move_1(dx, dy float64) {
    v.X += dx
    v.Y += dy
}

func (v Vertex) Move_2(dx, dy float64) {
    v.X += dx
    v.Y += dy
}

func Move_3(v *Vertex, dx, dy float64) {
    v.X += dx
    v.Y += dy
}

func Move_4(v Vertex, dx, dy float64) {
    v.X += dx
    v.Y += dy
}

func main() {
    var v Vertex
    v.X, v.Y = 0, 0
    v.Move_1(1, 1)
    fmt.Println(v.X, v.Y)
    p := &v
    p.Move_1(1, 1)
    fmt.Println(v.X, v.Y)
    v.Move_2(1, 1)
    fmt.Println(v.X, v.Y)
    Move_3(&v, 1, 1)
    fmt.Println(v.X, v.Y)
    Move_4(v, 1, 1)
    fmt.Println(v.X, v.Y)
}

Program output:

1 1
2 2
2 2
3 3
3 3

Interface (interface)

An interface is a set of method signatures; a variable of interface type can hold any value that implements those methods.

Go interfaces are implemented implicitly—no explicit keyword is required.

The empty interface ( interface{}) can hold values of any type.

Type assertions retrieve the underlying concrete value and can optionally report success.

type MyFloat float64

func (f MyFloat) Abs() float64 {
    if f < 0 {
        return float64(-f)
    }
    return float64(f)
}

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

type Abser interface {
    Abs() float64
}

func main() {
    var a Abser
    f := MyFloat(-math.Sqrt2)
    v := Vertex{3, 4}
    a = f   // MyFloat implements Abs
    a = &v  // *Vertex implements Abs
}
var i interface{} = "hello"
// Assert that i holds a string
s := i.(string)
fmt.Println(s)

// Safe assertion returning value and ok flag
s, ok := i.(string)
fmt.Println(s, ok)

f, ok := i.(float64)
fmt.Println(f, ok)

// This will panic because i does not hold a float64
f = i.(float64)
fmt.Println(f)

Program output:

hello
hello true
0 false
panic: interface conversion: interface {} is string, not float64
......
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendfunctionsclosuresmethodsInterfaces
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.