Sobes.tech
Junior — Middle

What is the difference between a structure without methods and an interface in a programming language?

sobes.tech AI

Answer from AI

In Go, a struct is a concrete data type that contains a set of fields (variables). It describes how data is organized, but by itself, it does not contain behavior.

An interface in Go describes a set of methods that a type must implement to satisfy the interface. An interface does not contain data, only method signatures.

Main differences:

  • Struct — is a concrete implementation with fields.
  • Interface — is an abstraction that describes behavior through methods.
  • A struct can implement one or more interfaces if it has the corresponding methods.

Example:

// Struct without methods
type User struct {
    Name string
    Age  int
}

// Interface with a method
type Greeter interface {
    Greet() string
}

// Implementation of the interface
func (u User) Greet() string {
    return "Hello, " + u.Name
}

Here, User is a struct with fields, and Greeter is an interface describing behavior. Without the Greet method, the User struct does not implement the Greeter interface.

What is the difference between a structure without… - sobes.tech