Understanding Three Key Features of Go Interfaces
The article explains Go's static typing, shows how interface types are method sets—including the empty interface—demonstrates type assertions, and walks through using the reflect package to inspect and modify values, highlighting settable constraints and struct field updates.
Types and Interfaces
Go is a statically typed language; each variable has a concrete type such as int, float32, or a user‑defined type. For example:
type MyInt int
var i int
var j MyIntVariables i and j have distinct static types and cannot be assigned to each other without conversion.
Interface types are collections of method signatures. Any 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) }An io.Reader variable can hold any value that has a Read method:
var r io.Reader
r = os.Stdin
r = bufio.NewReader(r)
r = new(bytes.Buffer)The variable’s static type remains io.Reader regardless of the concrete value assigned.
The empty interface interface{} has no methods and can hold any value because every type satisfies it.
Interface Representation
According to Russ Cox’s blog, an interface value stores a pair: the concrete value and its type description. Example:
var r io.Reader
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil { return nil, err }
r = ttyHere r holds the concrete *os.File value and its full type information.
A type assertion extracts the concrete type:
var w io.Writer
w = r.(io.Writer)The assertion succeeds because the underlying value implements Writer. The empty interface can hold any value without a need for assertion.
1. From Interface to Mapping Object
The reflect package provides TypeOf and ValueOf to retrieve the type and value stored in an interface.
package main
import (
"fmt"
"reflect"
)
func main() {
var f float64 = 13.4
fmt.Println(reflect.TypeOf(f))
fmt.Println("Hello, playground")
}Output shows the type float64. Internally, reflect.TypeOf receives the value via an empty interface. fmt.Println(reflect.ValueOf(f)) Methods such as Kind, Int, Float, and SetInt / SetFloat allow inspection and (cautiously) modification of values.
2. From Mapping Object to Interface Value
The Interface() method converts a reflect.Value back to an interface{}:
y := v.Interface().(float64)
fmt.Println(y)Formatting functions like fmt.Printf can accept the interface value directly, preserving the underlying type information.
3. Changing Interface Objects – Settable Values
Only addressable (settable) values can be modified via reflection. Attempting to call SetFloat on a non‑settable value panics:
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1) // panic: reflect.Value.SetFloat using unaddressable valueUsing CanSet reveals settable status. To obtain a settable value, pass a pointer to reflect.ValueOf and then call Elem():
var x float64 = 3.4
p := reflect.ValueOf(&x)
fmt.Println("type of p:", p.Type())
fmt.Println("settability of p:", p.CanSet()) // false
v := p.Elem()
fmt.Println("settability of v:", v.CanSet()) // true
v.SetFloat(7.1)
fmt.Println(v.Interface()) // 7.1
fmt.Println(x) // 7.1Thus the underlying variable x is updated.
Struct Field Modification
Reflection can also modify exported struct fields when the struct is addressable:
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())
}
s.Field(0).SetInt(77)
s.Field(1).SetString("Sunset Strip")
fmt.Println("t is now", t)Only exported fields are settable; attempting to modify unexported fields results in an error.
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.
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.
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.
