Visibilidade e pub
Nesta página
Em Zolo, tudo que não é marcado com pub é privado ao arquivo onde foi
declarado. Outro módulo que importar o arquivo só enxerga os itens públicos —
funções, constantes, structs, enums, traits e newtypes seguem a mesma regra.
O módulo de suporte lib_demo.zolo ilustra isso bem: greet, add, sub,
get_pi e VERSION são públicos; internal_helper não tem pub e permanece
invisível para fora:
Apenas os itens marcados pub aparecem na lista de use. Tentar importar
internal_helper causaria um erro de compilação.
// 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.
}
A regra é simples: se você quer que outros arquivos usem um item, adicione
pub. Se ele é detalhe de implementação, não adicione — o compilador vai
recusar qualquer tentativa de acesso externo.
pub const VERSIONexporta a constante.const VERSION(sempub) ficaria oculta — mesmo que esteja emlib_demo.zolo, nenhum outro arquivo poderia referenciá-la.
Veja também