Go الدورة

Go Structs, Methods, and Interfaces

دروس Python 3 للمبتدئين.

Defining a Struct

Structs are Go's way of grouping related data together — similar to classes in other languages:

type Person struct {
    Name string
    Age  int
    Email string
}

// Create a struct instance
alice := Person{Name: "Alice", Age: 30, Email: "alice@example.com"}
fmt.Println(alice.Name) // Alice

Methods on Structs

type Rectangle struct {
    Width  float64
    Height float64
}

// Value receiver
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// Pointer receiver (can modify the struct)
func (r *Rectangle) Scale(factor float64) {
    r.Width *= factor
    r.Height *= factor
}

rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area()) // 15
rect.Scale(2)
fmt.Println(rect.Area()) // 60

Interfaces

An interface defines a set of method signatures. Any type that implements all the methods satisfies the interface — no explicit declaration needed:

type Shape interface {
    Area() float64
    Perimeter() float64
}

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 printShape(s Shape) {
    fmt.Printf("Area: %.2f, Perimeter: %.2f
", s.Area(), s.Perimeter())
}

Embedding (Composition)

type Animal struct {
    Name string
}

func (a Animal) Speak() string {
    return a.Name + " makes a sound"
}

type Dog struct {
    Animal          // embedded struct
    Breed string
}

d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
fmt.Println(d.Speak()) // Rex makes a sound