Fundamentals 11 min read

Understanding Go Functions, Methods, Closures, and Interfaces

The article explains Go's core language constructs—functions (including parameter rules, multiple return values, named returns, and closures), methods on structs, and interfaces—illustrated with code examples, and then introduces common Go command‑line tools such as go build, install, get, doc, test, list and fix.

Golang Shines
Golang Shines
Golang Shines
Understanding Go Functions, Methods, Closures, and Interfaces

Functions

In Go, a function can have no parameters or any number of parameters. When consecutive parameters share the same type, the type can be omitted for all but the last parameter. A function (or variable) whose name starts with an uppercase letter is exported.

func add(x, y int) int {
    return x + y
}

Functions can return any number of values. Return values may be named, which makes them behave like variables defined at the top of the function; a bare return returns the current values of those variables.

func swap(x, y string) (string, string) {
    return y, x
}

Functions are first‑class values: they can be passed as arguments and returned from other functions.

func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

Closures

A closure is a record that stores a function together with the environment in which the function was created. The environment captures external variables that the function may read or modify.

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)()
    for i := 0; i < 5; i++ { fmt.Printf("%d ", test_3(1)(i)) }
    fmt.Println()
    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

Methods

Go has no classes, but methods can be defined for any type, typically a struct. A method is a function with a special receiver argument 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.

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) // 1 1
    p := &v
    p.Move_1(1, 1)
    fmt.Println(v.X, v.Y) // 2 2
    v.Move_2(1, 1)
    fmt.Println(v.X, v.Y) // 2 2 (no change)
    Move_3(&v, 1, 1)
    fmt.Println(v.X, v.Y) // 3 3
    Move_4(v, 1, 1)
    fmt.Println(v.X, v.Y) // 3 3 (receiver passed by value)
}

Program output:

1 1
2 2
2 2
3 3
3 3

Interfaces

An interface is a set of method signatures. Any type that implements all those methods satisfies the interface implicitly—no implements keyword is required.

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
    _ = a
}

The empty interface ( interface{}) holds values of any type because every type implements zero methods. Type assertions retrieve the concrete value and report success.

var i interface{} = "hello"
s, ok := i.(string)          // s == "hello", ok == true
f, ok := i.(float64)          // ok == false, f == 0
// s, _ = i.(float64) would panic

Program output:

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

Go Command‑Line Tools

The article also provides a concise overview of the most frequently used Go commands:

go build – compiles packages and their dependencies.

go install – compiles and installs a package and its dependencies.

go get – downloads or updates remote packages and installs them.

go doc and godoc – display documentation for Go entities; godoc is a powerful tool bundled since Go 1.5.

go test – runs package‑level tests.

go list – lists information about specified packages.

go fix (or go tool fix) – rewrites old Go source code to newer syntax.

These commands form the essential toolkit for building, testing, and maintaining Go projects.

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.

GofunctionsclosuresCommand-line Toolsmethodsinterfaces
Golang Shines
Written by

Golang Shines

We share daily the latest Golang technical articles, practical resources, language news, tutorials, and real-world projects to help everyone learn and improve.

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.