Fundamentals 15 min read

Understanding Go Types, Interfaces, and Reflection: A Deep Dive

This article explains Go's static type system, how types and interfaces work, the role of the empty interface, and demonstrates using the reflect package to inspect and modify values, including structs, with practical code examples and type assertions.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Understanding Go Types, Interfaces, and Reflection: A Deep Dive

Types and Interfaces

Go is a statically typed language, so every variable has a fixed type at compile time, such as int, float32, or a user‑defined type like MyType.

type MyInt int
var i int
var j MyInt

Variable i has type int and j has type MyInt. Although their underlying types are the same, they cannot be assigned to each other without conversion.

An important kind of type is the interface type, which is a set of method signatures. Any concrete value that implements those methods can be stored in an interface variable, e.g., io.Reader and io.Writer from the io package.

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

Any variable declared as io.Reader or io.Writer can call the corresponding methods. For example:

var r io.Reader
r = os.Stdin
r = bufio.NewReader(r)
r = new(bytes.Buffer)

Regardless of the concrete value assigned, the variable r always has the static type io.Reader. Go also has the empty interface interface{}, which has no methods and can hold a value of any type.

Interface Representation

According to Russ Cox, an interface variable stores a pair: the concrete value and its type description. For example:

var r io.Reader
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
    return nil, err
}
r = tty

Here r contains the value tty and the type *os.File. A type assertion can extract the concrete type:

var w io.Writer
w = r.(io.Writer)

The assertion states that the value stored in r implements io.Writer, allowing w to hold the same value and type.

var empty interface{}
empty = w

The empty interface can hold any value, including w, without needing a type assertion.

1. From Interface to Reflect Value

The reflect package provides Type and Value types to inspect interface values. Example:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var f float64 = 13.4
    fmt.Println(reflect.TypeOf(f))
    fmt.Println("Hello, playground")
}

Output:

float64
Hello, playground
reflect.TypeOf

receives the value via an empty interface, extracts its type, and reflect.ValueOf extracts the value itself.

var f float64 = 13.4
fmt.Println(reflect.ValueOf(f))

Output:

13.4
Value

provides methods such as Type(), Kind(), and conversion helpers like Int() and Float():

var f float64 = 13.44444
v := reflect.ValueOf(f)
fmt.Println(v)
fmt.Println(v.Type())
fmt.Println(v.Kind())
fmt.Println(v.Float())

Output:

13.444444444444445
float64
float64
13.444444444444445

Methods like SetInt and SetFloat can modify values, but only when the Value is settable.

2. From Reflect Value to Interface

The Interface() method converts a reflect.Value back to an interface{} value:

y := v.Interface().(float64)
fmt.Println(y)

Printing the interface directly works because formatting functions use the stored type information:

fmt.Println(v.Interface())
fmt.Printf("value is %e
", v.Interface())

Output: 3.4e+00 Thus Interface() is essentially the inverse of ValueOf.

3. Changing Interface Values Requires Settable Values

Attempting to modify a non‑addressable value panics:

var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1) // panic: reflect.Value.SetFloat using unaddressable value

Use CanSet() to check if a Value is mutable:

var x float64 = 3.4
v := reflect.ValueOf(x)
fmt.Println("settability of v:", v.CanSet())

Output: settability of v: false Obtaining a settable Value requires a pointer:

var x float64 = 3.4
p := reflect.ValueOf(&x)
fmt.Println("type of p:", p.Type())
fmt.Println("settability of p:", p.CanSet())

Output:

type of p: *float64
settability of p: false

Calling Elem() on the pointer yields a settable value:

v := p.Elem()
fmt.Println("settability of v:", v.CanSet())

Output: settability of v: true Now v.SetFloat(7.1) updates the original variable:

v.SetFloat(7.1)
fmt.Println(v.Interface())
fmt.Println(x)

Output:

7.1
7.1

Struct

Reflection can also modify struct fields when the struct is addressable. Example:

type T struct {
    A int
    B string
}

t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
    f := s.Field(i)
    fmt.Printf("%d: %s %s = %v
", i, typeOfT.Field(i).Name, f.Type(), f.Interface())
}

Output:

0: A int = 23
1: B string = skidoo

Only exported fields are settable. Using the settable Value, fields can be changed:

s.Field(0).SetInt(77)
s.Field(1).SetString("Sunset Strip")
fmt.Println("t is now", t)

Result:

t is now {77 Sunset Strip}
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.

GoReflectiontypestype assertionstructInterfacesempty interface
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.