Types?
-
Go is statically typed language means every variable's type is fixed at
compile time, which helps catch errors early and makes code reliable.
Types of types
| Type | Description |
|---|---|
| 1. Basic Type |
int, float64, bool, string
|
| 2. Aggregate Types |
1. Arrays:An array is a fixed-size sequence of elements of
the same type.
2. struct
|
| Reference Types |
Pointers: variable that stores the memory address of another
variable (&) slices: maps functions channels |
4. Interface
Interface only declares the functions those should be implemented by
concrete types. Similar to
Abstract Class C++98,
Concepts in C++20.
C++: A class must explicitly inherit from the abstract class (class Dog
: public Animal)
Go follows duck typing(If it walks like a duck and quacks like a
duck, it's a duck), What it means is if type in Go implements all
methods of interface, it automatically implements the interface(no need
to provide implements or extends keyword)
package main
import "fmt"
// 1. Define the interface (The Contract)
type Speaker interface { <<<<<< See Keyword interface
Speak() string // Pure behavior, no implementation, no variables
}
// 2. Define a concrete type
type Dog struct {
Name string // Structs hold the data
}
// 3. Implement the method (Implicitly!)
// There is no mention of "Speaker" here. Go just figures it out.
func (d Dog) Speak() string {
return "Woof!"
}
type Robot struct{}
func main() {
// A variable of interface type
var s Speaker
s = Dog{Name: "Buddy"} // Valid! Dog implements Speak()
fmt.Println(s.Speak())
// s = Robot{}
// ^ UNCOMMENTING THIS WILL CAUSE A COMPILER ERROR:
// "cannot use Robot{} as Speaker value: Robot does not implement Speaker (missing method Speak)"
}
Restrictions on Go Interfaces
1. Interface can have Methods only, variables, constants, or data fields
should not be present
2. Cannot write the body ({ ... }) of a function inside an interface.
3. Implementing type must match the method name, parameters, and return
types exactly
Use case of interface
| Use Case | Explanation |
|---|---|
| Multiple Structs, One Interface ie (Polymorphism) |
Allowing different structs to be treated as the same type because
they all implement the same functions. Eg: A database interface. You might have a MySQL struct and a MongoDB struct. Both implement a Save() function.
|
| Decoupling and Testing (Mocking) |
Interface Pollution Problem
-
Creating interfaces where they aren't actually needed. ie creating
interface for every class
Symptoms of Interface Pollution
1. One-to-One Mapping: Every single struct has a corresponding interface
2.Harder Navigation: In an IDE, clicking "Go to Definition" on a method takes you to the interface definition rather than the actual code doing the work.
| Polluted Interface | Good Interface |
|---|---|
|
|