Visibilidad y pub
En esta página
En Zolo, todo lo que no está marcado con pub es privado al archivo donde
fue declarado. Otro módulo que importe el archivo solo verá los elementos
públicos — funciones, constantes, structs, enums, traits y newtypes siguen la
misma regla.
El módulo de soporte lib_demo.zolo ilustra esto bien: greet, add, sub,
get_pi y VERSION son públicos; internal_helper no tiene pub y permanece
invisible desde fuera:
Solo los elementos marcados con pub aparecen en la lista de use. Intentar
importar internal_helper causaría un error de compilación.
// Feature: visibility — `pub` exports, no `pub` is private
// Syntax: `pub fn`, `pub const`, `pub struct`, etc. make the
// item visible to other modules. Without `pub`, it is restricted to
// the file.
// When to use: encapsulate internal details, expose only the API.
mod lib_demo
// Only the public API is importable.
use lib_demo::{greet, add, get_pi, VERSION}
fn main() {
greet("public api")
print("add(1,2) = {add(1, 2)}")
print("pi = {get_pi()}")
print("version = {VERSION}")
// expected:
// Hello, public api!
// add(1,2) = 3
// pi = 3.14159
// version = 1.0.0
// Note: `internal_helper` is in lib_demo.zolo WITHOUT `pub`,
// so it cannot be imported or called from here.
// Trying `use lib_demo::internal_helper` or
// `lib_demo::internal_helper()` is a design error — the
// function belongs only to the module.
}
La regla es simple: si quieres que otros archivos usen un elemento, añade pub.
Si es un detalle de implementación, no lo añadas — el compilador rechazará
cualquier intento de acceso externo.
pub const VERSIONexporta la constante.const VERSION(sinpub) quedaría oculta — aunque esté enlib_demo.zolo, ningún otro archivo podría referenciarla.
Consulta también