When developing in Go, understanding the distinction between interfaces and structs is key to designing robust and flexible applications. This article will guide you through the differences between structs and interfaces, highlighting when and why you should use one over the other.

Understanding Structs in Go

Structs in Go are used to create data structures that group different properties related to an item. Structs are invaluable for situations where you need detailed information about your data.

Basic Example of a Struct

package main
import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 30}
    fmt.Println(p)
}

In this basic example, we define a Person struct with two fields: Name and Age. Structs help manage related data more intuitively while allowing easy access and manipulation of each field.

Intermediate Struct Usage

package main
import "fmt"

type Car struct {
    Make  string
    Model string
    Year  int
}

func printCarDetails(c Car) {
    fmt.Printf("%s %s, Year: %d\n", c.Make, c.Model, c.Year)
}

func main() {
    myCar := Car{Make: "Toyota", Model: "Corolla", Year: 2020}
    printCarDetails(myCar)
}

Here, we use a struct to encapsulate information about a car. printCarDetails demonstrates how to pass structs to functions to operate on their data conveniently.

Understanding Interfaces in Go

Interfaces in Go define a set of method signatures but do not contain the implementations. They are akin to contracts that any data type can satisfy by implementing the methods defined by the interfaces.

Basic Example of an Interface

package main
import "fmt"

type Describer interface {
    Describe() string
}

type Product struct {
    Name string
    Price float64
}

func (p Product) Describe() string {
    return fmt.Sprintf("%s costs %.2f", p.Name, p.Price)
}

func main() {
    var d Describer
    d = Product{Name: "Laptop", Price: 1299.99}
    fmt.Println(d.Describe())
}

In this code, the Describer interface is satisfied by the Product struct through the implementation of the Describe method. By assigning a Product to d, which is of the Describer type, we utilize <<,ploy>s>=<N