Fundamentals 14 min read

Mastering Go Types and Interfaces: A Deep Dive into Reflection

This article explains Go's static type system, introduces custom types and interface definitions, demonstrates how interfaces store concrete values, and shows how the reflect package can inspect and modify values, covering empty interfaces, type assertions, and mutable reflect values with practical code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Go Types and Interfaces: A Deep Dive into Reflection

Types and Interfaces

Go is a statically typed language where each variable has a fixed type at compile time, such as int, float32, or a user‑defined type like MyInt. Example:

type MyInt int
var i int
var j MyInt

Variables i and j have distinct types and cannot be assigned to each other without conversion. Interface types are collections of method signatures; any concrete type that implements those methods can be stored in an interface variable. Common examples are 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)
}

An io.Reader variable can hold any value that provides a Read method:

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

The variable r always retains the static type io.Reader, even though the underlying concrete value may change. The empty interface interface{} has no methods and can hold a value of any type.

Interface Representation

An interface value stores a pair: the concrete value and its type description. For example, assigning a file to an io.Reader stores the file pointer and its full type information, allowing method calls defined by the interface.

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

Type assertions can extract the concrete type from an interface:

var w io.Writer
w = r.(io.Writer) // asserts that r's concrete value implements Writer

The empty interface can hold any value without needing an assertion.

1. From Interface to Reflect Value

The reflect package provides TypeOf and ValueOf to inspect an interface's dynamic type and value.

package main
import (
    "fmt"
    "reflect"
)
func main() {
    var f float64 = 13.4
    fmt.Println(reflect.TypeOf(f))   // float64
    fmt.Println(reflect.ValueOf(f)) // 13.4
}
ValueOf

returns a reflect.Value that can be queried for its kind, type, and underlying data.

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

Mutable operations such as SetInt or SetFloat require a settable reflect.Value, which is only possible when the value is addressable.

2. From Reflect Value to Interface

The Interface method converts a reflect.Value back to an interface{} containing the original concrete value.

y := v.Interface().(float64)
fmt.Println(y) // prints the float64 value

Formatting functions like fmt.Println or fmt.Printf can accept the empty interface and correctly render the underlying value.

3. Changing Interface Values

Attempting to modify a non‑addressable reflect.Value (e.g., one obtained from a plain variable) panics. Use reflect.ValueOf(&x) to obtain a settable value.

var x float64 = 3.4
p := reflect.ValueOf(&x) // pointer to x
v := p.Elem()               // dereferenced, settable
fmt.Println("settability of v:", v.CanSet()) // true
v.SetFloat(7.1)
fmt.Println(x) // 7.1

Struct Reflection

Reflect can also modify exported struct fields when given a pointer to the struct.

type T struct { A int; B string }
 t := T{23, "skidoo"}
 s := reflect.ValueOf(&t).Elem()
 s.Field(0).SetInt(77)
 s.Field(1).SetString("Sunset Strip")
 fmt.Println("t is now", t) // {77 Sunset Strip}

Only exported fields are settable. This demonstrates how Go's reflection bridges static types and dynamic inspection/modification.

Source: https://www.cnblogs.com/zhangboyu/p/7456663.html

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.

Reflectiontypesstatic typingInterfacesempty interfacereflect package
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.