Bloques impl y Métodos de Instancia
En esta página
Un bloque impl agrupa los métodos de instancia de un tipo. Cada método recibe
self como primer parámetro — la referencia al valor sobre el que se invocó el
método. Los métodos dentro del mismo impl pueden llamarse entre sí mediante
self.metodo():
current() lee el campo; doubled() llama a current() para componer el resultado.
// 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
Los métodos que devuelven valores nuevos siguen el estilo inmutable: calculan y devuelven una nueva instancia sin modificar la original. Esto facilita el razonamiento sobre el estado:
scaled(factor) devuelve un Rectangle nuevo — la instancia r no cambia.
// 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
Cuando el comportamiento necesita modificar el estado, asigna directamente al
campo con self.campo = nuevo_valor. El método puede devolver el valor resultante
o el propio self:
increment() y add(n) mutan self.value y devuelven el nuevo valor.
// 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
Desafío
En 02-instance-methods.zolo, agrega un método with_height(h) que devuelva un
nuevo Rectangle con el ancho original pero la altura h. Llámalo encadenado:
r.scaled(2.0).with_height(1.0).area().
Consulta también