interfaces Flashcards

(10 cards)

1
Q

Interface Basics

A
type Speaker interface {
    Speak() string
}

Key Points:
* Named collection of method signatures
* Types implicitly satisfy interfaces by implementing all methods
* Zero value: nil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Implicit Implementation

A
type Dog struct{}
func (d Dog) Speak() string { return "Woof!" }

var s Speaker = Dog{}  // Dog satisfies Speaker
fmt.Println(s.Speak()) // "Woof!"

Rule: No explicit implements keyword - satisfaction is automatic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Empty Interface (interface{})

A

Use Case: Accept any type

func logAnything(v interface{}) {
    fmt.Printf("%T: %v\n", v, v)
}
logAnything(42)       // int: 42
logAnything("hello")  // string: hello
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Type Assertions

A

Check Concrete Type:

var s Speaker = Dog{}
dog := s.(Dog)  // Extract Dog

Safe Check:

if dog, ok := s.(Dog); ok {
    fmt.Println(dog.Speak())
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Type Switches

A

Handle Multiple Types:

func describe(i interface{}) {
    switch v := i.(type) {
    case Dog:
        fmt.Println("Dog says:", v.Speak())
    case int:
        fmt.Println("Integer:", v)
    default:
        fmt.Printf("Unknown type %T\n", v)
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Common Interfaces

A

Built-in Examples:

type error interface { Error() string }
type Stringer interface { String() string }

Usage:

func (d Dog) String() string { return "I'm a dog" }
fmt.Println(Dog{}) // Calls String() automatically
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Interface Values

A

Under the Hood:
* Dynamic type + value (or nil)

var s Speaker  // nil interface
s = Dog{}      // type=Dog, value=Dog{}

Nil vs Nil Interface:

var d *Dog     // nil concrete value
var s Speaker = d  // s != nil (has type *Dog)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Best Practices

A
  1. Keep interfaces small (1-3 methods)
  2. Name interfaces with -er suffixes (Reader, Writer)
  3. Compose interfaces:
type ReadWriter interface {
    Reader
    Writer
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Interface Pitfalls

A

Watch For:
* Nil pointer dereference:

var s Speaker
s.Speak()  // PANIC: nil interface

Accidental shadowing:
var _ io.Writer = (*bytes.Buffer)(nil) // Compile-time check

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Real-World Examples

A

HTTP Handler:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

Sorting:

sort.Interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

Key Insight: Interfaces enable polymorphism and dependency injection in Go.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly