Pular para o conteúdo

Blocos impl e Métodos de Instância

Nesta página

Um bloco impl agrupa métodos de instância de um tipo. Cada método recebe self como primeiro parâmetro — a referência ao valor sobre o qual o método foi chamado. Métodos dentro do mesmo impl podem se chamar mutuamente via self.metodo():

current() lê o campo; doubled() chama current() para compor o resultado.

01-impl-block.zolo
Playground
// Feature: impl block — groups methods of a struct

// Syntax: `impl Type { fn method(self, ...) { ... } }`

// When to use: attach behavior to a type. Each impl block adds

// instance methods (which take `self`) or associated functions

// (no `self`, called via `Type::name(...)`).


struct Counter {
  value: int,
}

impl Counter {
  // Instance method: takes `self` as the first parameter.

  fn current(self) -> int {
    return self.value
  }
  // Another instance method — can call other methods on self.



  fn doubled(self) -> int {
    return self.current() * 2
  }
}

let c = Counter { value: 7 }
print(c.current())  // 7

print(c.doubled())  // 14

// expected:

// 7

// 14

Métodos que retornam novos valores seguem o estilo imutável: calculam e devolvem uma nova instância sem alterar a original. Isso facilita o raciocínio sobre estado:

scaled(factor) devolve um Rectangle novo — a instância r não muda.

02-instance-methods.zolo
Playground
// Feature: Instance methods — they use `self`

// Syntax: `fn method(self, args...) -> Ret { ... }`

// When to use: read/use instance data, or return a new modified

// instance (immutable style).


struct Rectangle {
  width: float,
  height: float,
}

impl Rectangle {
  fn area(self) -> float {
    return self.width * self.height
  }

  fn perimeter(self) -> float {
    return 2.0 * (self.width + self.height)
  }

  fn is_square(self) -> bool {
    return self.width == self.height
  }
  // Returns a NEW instance — functional immutable pattern.



  fn scaled(self, factor: float) -> Rectangle {
    return Rectangle { width: self.width * factor, height: self.height * factor }
  }
}

let r = Rectangle { width: 4.0, height: 5.0 }
print(r.area())  // 20

print(r.perimeter())  // 18

print(r.is_square())  // false


let big = r.scaled(2.0)
print(big.area())  // 80

// expected:

// 20

// 18

// false

// 80

Quando o comportamento precisa alterar o estado, atribua diretamente ao campo via self.campo = novo_valor. O método pode então retornar o valor resultante ou o próprio self:

increment() e add(n) mutam self.value e retornam o novo valor.

04-self-and-mutation.zolo
Playground
// Feature: `self` in methods — reading and mutating fields

// Syntax: `fn method(self, ...) { self.field = new_value }`

// When to use: read or directly modify the fields of the instance

// that received the call.


struct Counter {
  value: int,
}

impl Counter {
  fn new() -> Counter {
    return Counter { value: 0 }
  }
  // Direct mutation via self — updates the instance field.



  fn increment(self) -> int {
    self.value = self.value + 1
    return self.value
  }
  // Simple read.



  fn get(self) -> int {
    return self.value
  }

  fn add(self, n: int) -> int {
    self.value = self.value + n
    return self.value
  }
}

let c = Counter::new()
print(c.increment())  // 1

print(c.increment())  // 2

print(c.add(10))  // 12

print(c.get())  // 12

// expected:

// 1

// 2

// 12

// 12

Desafio

Em 02-instance-methods.zolo, adicione um método with_height(h) que devolve um novo Rectangle com a largura original mas a altura h. Chame-o encadeado: r.scaled(2.0).with_height(1.0).area().

Buscar no Zolo

9 resultados

enespt-br