How to define and use interfaces in Golang?
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.
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.

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:

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.

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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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.

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

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

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](https://img.php.cn/upload/article/001/246/273/175668570227460.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
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.

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.
