Interface vs Struct in Go: Key Differences and Usage
struct is a concrete data type used to group related fields, while an interface defines a set of method signatures without implementation. Structs hold data and implement behavior, whereas interfaces specify behavior that structs or other types must provide.Quick Comparison
Here is a quick side-by-side comparison of interface and struct in Go.
| Aspect | Struct | Interface |
|---|---|---|
| Purpose | Holds data fields | Defines method set (behavior) |
| Type | Concrete type | Abstract type |
| Can be instantiated? | Yes | No |
| Contains data? | Yes | No |
| Implements methods? | Yes, with code | No, only method signatures |
| Used for | Represent objects with data | Specify behavior contracts |
Key Differences
Structs in Go are used to group related data together into one unit. They are concrete types, meaning you can create variables of that type and store actual data. Structs can also have methods attached to them, which define behavior related to the data.
Interfaces, on the other hand, are abstract types that only specify a set of method signatures without any implementation. They describe what methods a type must have but not how those methods work. Any type (often a struct) that implements all the methods of an interface is said to satisfy that interface.
This means interfaces are used to define behavior and enable polymorphism, allowing different types to be treated the same way if they implement the same interface. Structs are used to hold data and implement the behavior defined by interfaces or their own methods.
Code Comparison
This example shows a struct defining a data type with a method.
package main import "fmt" type Person struct { Name string Age int } func (p Person) Greet() string { return "Hello, my name is " + p.Name } func main() { p := Person{Name: "Alice", Age: 30} fmt.Println(p.Greet()) }
Interface Equivalent
This example shows an interface defining behavior and a struct implementing it.
package main import "fmt" type Greeter interface { Greet() string } type Person struct { Name string Age int } func (p Person) Greet() string { return "Hello, my name is " + p.Name } func main() { var g Greeter g = Person{Name: "Alice", Age: 30} fmt.Println(g.Greet()) }
When to Use Which
Choose struct when you need to store and organize related data together and possibly add methods to operate on that data. Use interface when you want to define a set of behaviors that multiple types can implement, enabling flexible and reusable code through polymorphism.
In practice, structs hold your data and implement interfaces to provide specific behaviors. Interfaces let you write functions that work with any type that satisfies the interface, making your code more modular and testable.