Menu
Coddy logo textTech

Definindo Métodos em Structs

Parte da seção Programação Orientada a Objetos do Journey de GO da Coddy — lição 7 de 107.

Métodos em Go são funções com um argumento receptor especial que associa a função a um tipo struct.

Sintaxe de método

func (receiverName StructType) MethodName() ReturnType {
    // corpo do método
}

Defina uma struct com métodos

type Rectangle struct {
    Width  float64
    Height float64
}

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

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

Métodos com parâmetros

func (r Rectangle) Scale(factor float64) float64 {
    return r.Area() * factor
}

Chamando métodos

rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area())      // Saída: 15
fmt.Println(rect.Perimeter()) // Saída: 16
fmt.Println(rect.Scale(2))    // Saída: 30

O receptor (r Rectangle) permite acessar os campos da struct dentro do método usando a variável do receptor r. Métodos podem chamar outros métodos na mesma struct.

challenge icon

Desafio

Médio

Adicione três métodos à struct Circle:

  • Area — retorna math.Pi * radius * radius
  • Circumference — retorna 2 * math.Pi * radius
  • Describe — retorna uma string: "Circle with radius X.XX"

Folha de consulta

Métodos em Go são funções com um argumento receiver (receptor) especial que associa a função a um tipo struct.

Sintaxe do método:

func (receiverName StructType) MethodName() ReturnType {
    // method body
}

Exemplo com uma struct e métodos:

type Rectangle struct {
    Width  float64
    Height float64
}

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

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

Métodos podem aceitar parâmetros:

func (r Rectangle) Scale(factor float64) float64 {
    return r.Area() * factor
}

Chamando métodos:

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

O receiver permite que você acesse os campos da struct dentro do método. Métodos podem chamar outros métodos na mesma struct.

Experimente você mesmo

package main

import "fmt"

func main() {
    var radius float64
    fmt.Scan(&radius)

    c := Circle{Radius: radius}

    fmt.Printf("Area: %.2f\n", c.Area())
    fmt.Printf("Circumference: %.2f\n", c.Circumference())
    fmt.Printf("Description: %s\n", c.Describe())
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Programação Orientada a Objetos