Table of Contents
What is an interface in Go?
How to implement an interface
Empty interface: interface{} (pre-Go 1.18)
Type assertions and type switches
Best practices and tips
Example: Using standard library-style interfaces
Home Backend Development Golang How to define and use interfaces in Golang?

How to define and use interfaces in Golang?

Aug 01, 2025 am 07:10 AM
golang interface 接口定义

An interface in Go is a type that defines a set of method signatures, and any type implementing those methods automatically satisfies the interface without explicit declaration. 1. Define an interface with method signatures, like Speaker with Speak() string. 2. Implement the interface by providing the methods on any type, such as Dog and Cat structs with a Speak() method. 3. Use interface values interchangeably, as shown with a slice of Speaker holding both Dog and Cat. 4. Use any (or interface{}) to accept any type, but apply type assertions or type switches to retrieve the underlying type when needed. 5. Follow best practices: keep interfaces small, let them emerge naturally, use any sparingly, prefer value receivers, and leverage standard-library patterns like io.Writer. Interfaces in Go promote polymorphism, flexibility, and clean design by focusing on behavior rather than implementation, making code composable, reusable, and testable.

How to define and use interfaces in Golang?

In Go, interfaces are a powerful way to achieve polymorphism and decouple code. They allow you to define behavior without specifying implementation, making your code more flexible and reusable.

How to define and use interfaces in Golang?

What is an interface in Go?

An interface is a type that specifies a set of method signatures. Any type that implements all the methods in the interface automatically satisfies it — there’s no need to explicitly declare it. This is known as implicit implementation.

Here’s how you define a basic interface:

How to define and use interfaces in Golang?
type Speaker interface {
    Speak() string
}

This Speaker interface requires any implementing type to have a Speak() method that returns a string.


How to implement an interface

Any type (like a struct) can implement the interface by providing the required methods.

How to define and use interfaces in Golang?
type Dog struct {
    Name string
}

func (d Dog) Speak() string {
    return "Woof! I'm "   d.Name
}

type Cat struct {
    Name string
}

func (c Cat) Speak() string {
    return "Meow! I'm "   c.Name
}

Now both Dog and Cat satisfy the Speaker interface because they have a Speak() string method.

You can use them interchangeably:

func main() {
    animals := []Speaker{Dog{Name: "Buddy"}, Cat{Name: "Whiskers"}}

    for _, animal := range animals {
        fmt.Println(animal.Speak())
    }
}

Output:

Woof! I'm Buddy
Meow! I'm Whiskers

Note: The assignment to Speaker works because Go checks at compile time whether the types implement the required methods.


Empty interface: interface{} (pre-Go 1.18)

Before Go 1.18, the empty interface was written as interface{} and could hold any value since it has no methods:

var x interface{} = "hello"
var y interface{} = 42

As of Go 1.18 , you can use any as a more readable alias:

var x any = "hello"

Both interface{} and any mean the same thing.

Useful for functions that accept any type:

func Print(v any) {
    fmt.Println(v)
}

But remember: you’ll likely need type assertions or type switches to get the underlying value back.


Type assertions and type switches

Since interfaces hide concrete types, you may need to extract the original type.

Type assertion:

if dog, ok := animal.(Dog); ok {
    fmt.Println("Found a dog:", dog.Name)
}

Type switch:

switch v := animal.(type) {
case Dog:
    fmt.Println("It's a dog:", v.Name)
case Cat:
    fmt.Println("It's a cat:", v.Name)
default:
    fmt.Println("Unknown animal")
}

This is especially helpful when handling different behaviors based on the actual type.


Best practices and tips

  • Keep interfaces small: Go favors small, focused interfaces (like io.Reader, io.Writer).
  • Let interfaces emerge naturally: Don’t force types to satisfy large interfaces. Define interfaces where needed, not upfront.
  • Use interface{} (or any) sparingly: It loses type safety. Generics (introduced in Go 1.18) are often a better choice.
  • Prefer value receivers unless mutation is needed: Consistent receiver types help avoid accidental interface mismatches.

Example: Using standard library-style interfaces

Go’s standard library uses this pattern heavily. For example:

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

You can write a function that works with any writer:

func Greet(w io.Writer, name string) {
    fmt.Fprintf(w, "Hello, %s!\n", name)
}

Now it works with files, network connections, buffers, etc., as long as they implement Write.


Basically, interfaces in Go are about what a type can do, not what it is. You define them by the behavior they require, and types automatically satisfy them by implementing the methods. It keeps things simple, composable, and testable.

The above is the detailed content of How to define and use interfaces in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

How to manage packages and imports in Go? How to manage packages and imports in Go? Sep 01, 2025 am 02:10 AM

UseGomodulesbyrunninggomodinittocreateago.modfile,whichmanagesdependenciesandversions.2.Organizecodeintopackageswhereeachdirectoryisapackagewithaconsistentpackagename,preferablymatchingthedirectoryname,andstructureimportsbasedonthemodulepath.3.Import

How to implement a generic LRU cache in Go How to implement a generic LRU cache in Go Aug 18, 2025 am 08:31 AM

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

How to create a custom build tag in Go How to create a custom build tag in Go Aug 27, 2025 am 04:37 AM

CustombuildtagsinGoallowconditionalcompilationbasedonenvironment,architecture,orcustomscenariosbyusing//go:buildtagsatthetopoffiles,whicharethenenabledviagobuild-tags"tagname",supportinglogicaloperatorslike&&,||,and!forcomplexcondit

How to handle panics in a goroutine in Go How to handle panics in a goroutine in Go Aug 24, 2025 am 01:55 AM

Tohandlepanicsingoroutines,usedeferwithrecoverinsidethegoroutinetocatchandmanagethemlocally.2.Whenapanicisrecovered,logitmeaningfully—preferablywithastacktraceusingruntime/debug.PrintStack—fordebuggingandmonitoring.3.Onlyrecoverfrompanicswhenyoucanta

How to use Go with Apache Kafka How to use Go with Apache Kafka Aug 20, 2025 am 11:25 AM

The key to integrating with ApacheKafka with Go is to select the right client library and properly configure producers and consumers. First of all, it is recommended to use the segmentio/kafka-go library. Because it is concise and conforms to the Go language habits, after installation through gogetgithub.com/segmentio/kafka-go, you can create Writer to send messages and set Addr, Topic and Balancer policies; then configure Reader to realize message consumption by specifying Brokers, Topic and GroupID, support consumer groups and manual partition allocation; be sure to use context to control timeouts, enable TLS/SASL to ensure security,

How to convert []int to []uint8 (byte array) in Go How to convert []int to []uint8 (byte array) in Go Sep 01, 2025 am 08:15 AM

This article explores how to convert []int slices to []uint8 (byte array) in Go. Given that the size of the int type in Go is platform-related (32-bit or 64-bit), the article details how to use the reflect package to dynamically obtain the int size, and combine the encoding/binary package to convert efficiently and safely in a large-endian manner, providing specific code examples and precautions to help developers cope with cross-platform data conversion challenges.

Go language concurrent programming: Understanding and using sync.WaitGroup Go language concurrent programming: Understanding and using sync.WaitGroup Aug 31, 2025 am 07:48 AM

sync.WaitGroup is an important primitive for concurrent synchronization in Go language. It allows the main goroutine to wait for a group of sub goroutines to be executed. Through the counter mechanism, WaitGroup can ensure that all concurrent tasks are completed and the program continues to be executed, effectively avoiding race conditions and resource leakage, and is a key tool for building robust concurrent applications.

See all articles