OSGo.009: Go Interfaces — Implicit Satisfaction, Method Sets and Typed Nil

Cropped editorial photograph of server connections; source Abigor / Wikimedia Commons CC BY-SA 3.0.

Open-Source Go Programming • Foundational • Estimated study time: 45 minutes.

A monitoring application may obtain temperature readings from a local sensor, a remote service or a test fixture. The rest of the application should not need to understand how each source works. A Go interface specifies the behavior required by the caller. This lesson extends structs and receiver semantics.

Objectives

Define an interface and its method set; demonstrate implicit satisfaction; substitute implementations; distinguish nil interfaces from interfaces containing typed nil pointers; and handle missing or failed readings without inventing a zero-temperature measurement.

Video: Why Go Interfaces? An instructional introduction to interface behavior and motivation.

The interface contract

An interface defines methods and their signatures. A concrete type satisfies a basic interface when its method set includes all required methods. No implements keyword is necessary. For a defined type T, its value method set includes methods with receiver T; *T includes both value and pointer receiver methods. The Go specification is the authoritative reference. A compile-time check such as var _ Sensor = Fixed{} documents the intended relationship without allocating a sensor for runtime use.

Rear of a rack at NERSC
Networked servers can expose different telemetry mechanisms; a software interface can present uniform behavior to a caller. Derrick Coetzee / Wikimedia Commons, CC0. Illustrative photo, not the lab hardware.

Worked example: a common telemetry reader

This example extends the multiple return values and error handling lesson. Fixed returns a synthetic temperature; Offline returns an explicit error. The report function depends only on the Sensor contract. The interface slice uses principles from arrays and slices.

package main

import (
    "errors"
    "fmt"
)

type Sensor interface{ Read() (float64, error) }
type Fixed struct{ Celsius float64 }

func (f Fixed) Read() (float64, error) { return f.Celsius, nil }

type Offline struct{}

func (Offline) Read() (float64, error) { return 0, errors.New("offline") }

var _ Sensor = Fixed{}
var _ Sensor = Offline{}

func report(s Sensor) string {
    if s == nil {
        return "missing sensor"
    }
    v, err := s.Read()
    if err != nil {
        return "error: " + err.Error()
    }
    return fmt.Sprintf("%.1f C", v)
}
func main() {
    for _, s := range []Sensor{Fixed{24.5}, Offline{}, nil} {
        fmt.Println(report(s))
    }
    var p *Fixed
    var s Sensor = p
    fmt.Println("typed nil interface:", s == nil)
}

Save as main.go. Run go vet main.go and go run main.go. Both completed successfully in the local Go environment. Actual program output:

24.5 C
error: offline
missing sensor
typed nil interface: false

The typed-nil trap

An ordinary nil interface has no dynamic type or value. Assigning a nil *Fixed pointer to Sensor sets a dynamic type while leaving the pointer nil. The resulting interface is not equal to nil. Do not call its value-receiver Read method: dereferencing a nil pointer can panic. The Go FAQ describes the same problem for errors. Return an explicit nil interface when there is no implementation, or design a pointer-receiver method that handles nil deliberately.

Community discussion of interfaces and typed-nil behavior. Treat the specification and FAQ as authoritative.

Measurement and operational safety

For a real monitoring batch, mean temperature is T̄ = (Σ Ti) / n, where Ti is a valid reading in degrees Celsius and n is the count of valid readings. Example: 24.5 °C and 25.5 °C produce a 25.0 °C mean. A failed reading is not a measured 0 °C and must not silently enter the average. Return an error or missing-state indicator if n = 0. Use map lookups to identify configured sensor sources. Test with synthetic values before connecting operational equipment; avoid using this demonstration as an equipment control or alarm system.

Exercises and answer key

A. Does Fixed need an implements declaration? B. What happens if Read is defined only on *Fixed? C. Why is a nil *Fixed assigned to Sensor not a nil interface? D. What does report(Offline{}) return? E. Calculate the mean of 20, 22 and 24 °C, excluding one failed reading. F. How could you add an HTTP sensor without changing report?

Answers: A. No. B. *Fixed satisfies the interface; Fixed does not. C. It contains a dynamic type. D. error: offline. E. 22 °C. F. Implement Read() (float64, error) on the new type and supply that implementation to report. Further reading: A Tour of Go: Interfaces.

Cover photograph: Abigor / Wikimedia Commons, CC BY-SA 3.0; cropped to 1200 × 630.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply