type Notifier interface {
Send(message string) error
} type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type Closer interface {
Close() error
} type FileSystem interface {
Open(name string) (File, error)
Remove(name string) error
Stat(name string) (FileInfo, error)
} type Notifier interface {
Send(message string) error
}
// EmailNotifier отправляет уведомления по email.
type EmailNotifier struct {
from string
}
// Send отправляет email.
func (e EmailNotifier) Send(message string) error {
fmt.Printf("Sending email from %s: %s\n", e.from, message)
return nil
} func notify(n Notifier, message string) {
err := n.Send(message)
if err != nil {
fmt.Printf("Failed to send: %v\n", err)
}
}
func main() {
email := EmailNotifier{from: "admin@example.com"}
notify(email, "Hello via email!")
} // SMSNotifier отправляет уведомления по SMS.
type SMSNotifier struct {
phoneNumber string
}
// Send отправляет SMS.
func (s SMSNotifier) Send(message string) error {
fmt.Printf("Sending SMS to %s: %s\n", s.phoneNumber, message)
return nil
} sms := SMSNotifier{phoneNumber: "+1234567890"}
notify(sms, "Hello via SMS!") type Counter struct {
count int
}
func (c *Counter) Increment() { // ← pointer receiver
c.count++
}
type Incrementer interface {
Increment()
}
var inc Incrementer
c := Counter{}
inc = &c // ✅ Работает, *Counter реализует Incrementer
// inc = c // ❌ Ошибка: Counter не реализует Incrementer func (r Rectangle) Area() float64 { // ← value receiver
return r.Width * r.Height
}
rect := Rectangle{Width: 10, Height: 5}
var s Shape
s = rect // ✅ Работает
s = &rect // ✅ Тоже работает type Shape interface {
Area() float64
Perimeter() float64
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
} func printShapeInfo(s Shape) {
fmt.Printf("Area: %.2f\n", s.Area())
fmt.Printf("Perimeter: %.2f\n", s.Perimeter())
}
func main() {
rect := Rectangle{Width: 10, Height: 5}
circle := Circle{Radius: 7}
printShapeInfo(rect) // ← Работает с прямоугольником
printShapeInfo(circle) // ← Работает с кругом
} func calculateTotalArea(shapes []Shape) float64 {
total := 0.0
for _, shape := range shapes {
total += shape.Area()
}
return total
}
func main() {
shapes := []Shape{
Rectangle{Width: 10, Height: 5},
Circle{Radius: 7},
Rectangle{Width: 3, Height: 4},
}
total := calculateTotalArea(shapes)
fmt.Printf("Total area: %.2f\n", total)
} var i interface{}
i = 42 // ← int
i = "hello" // ← string
i = true // ← bool
i = []int{1, 2} // ← slice var i any
i = 42
i = "hello" func printAny(value any) {
fmt.Printf("Value: %v, Type: %T\n", value, value)
}
func main() {
printAny(42)
printAny("hello")
printAny([]int{1, 2, 3})
} var i any = "hello"
s := i.(string) // ← Извлекаем string
fmt.Println(s) // "hello" var i any = 42
s := i.(string) // panic: interface conversion: interface {} is int, not string var i any = 42
s, ok := i.(string)
if ok {
fmt.Println("It's a string:", s)
} else {
fmt.Println("Not a string") // ← Выполнится этот блок
} func describe(i any) {
switch v := i.(type) {
case int:
fmt.Printf("Integer: %d\n", v) // ← v имеет тип int
case string:
fmt.Printf("String: %s\n", v) // ← v имеет тип string
case bool:
fmt.Printf("Boolean: %t\n", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
}
func main() {
describe(42)
describe("hello")
describe(true)
describe(3.14)
} func process(i any) {
switch v := i.(type) {
case int, int64:
// v имеет тип any, нужен type assertion для использования
fmt.Printf("Integer type: %T\n", v)
case string:
// v имеет тип string
fmt.Printf("String: %s\n", v)
}
} type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader // ← Встраивание интерфейса Reader
Writer // ← Встраивание интерфейса Writer
} type ReadWriteCloser interface {
Reader
Writer
Closer
}