This program shows how an interface lets a function accept any type that can greet. Person has a Greet method, so it works with sayHello.
Go
package main
import"fmt"// Define an interface
type Greeter interface {
Greet() string
}
// Define a type that implements Greeter
type Person struct {
name string
}
func (p Person) Greet() string {
return"Hello, " + p.name
}
// Function that accepts any Greeter
func sayHello(g Greeter) {
fmt.Println(g.Greet())
}
func main() {
p := Person{name: "Alice"}
sayHello(p) // Person implements Greeter
}
OutputSuccess
Important Notes
Interfaces help separate what something does from how it does it.
In Go, you don't need to declare that a type implements an interface; it happens automatically.
Summary
Interfaces define behavior without details.
They let different types work together easily.
They make code flexible and easier to change.
Practice
(1/5)
1. Why are interfaces used in Go programming?
easy
A. To define a set of methods that different types can implement
B. To store data in a fixed format
C. To create variables with fixed values
D. To perform arithmetic operations
Solution
Step 1: Understand what interfaces represent
Interfaces in Go define behavior by specifying method signatures without implementation.
Step 2: Recognize the purpose of interfaces
They allow different types to implement the same set of methods, enabling flexible and interchangeable code.
Final Answer:
To define a set of methods that different types can implement -> Option A
Quick Check:
Interfaces define behavior = D [OK]
Hint: Interfaces describe behavior, not data storage [OK]
Common Mistakes:
Thinking interfaces store data
Confusing interfaces with variables
Assuming interfaces perform calculations
2. Which of the following is the correct way to declare an interface in Go?
D. var Reader interface = { Read(p []byte) (n int, err error) }
Solution
Step 1: Recall Go syntax for interface declaration
Interfaces are declared using the 'type' keyword followed by the interface name and the 'interface' keyword with method signatures inside curly braces.