Conceptadvanced
Opaque type
Also called opaque data type, abstract type, opaque pointer, incomplete type, opaque return type, opaque type alias, impl Trait, some Protocol, pImpl.
An opaque type hides its representation from the code that uses it, so that code can work with the values only through the operations that the defining module gives.
- Applies to
- core-languages
Idea
A module often needs a type whose inside it may change later, or whose values must obey a rule, such as "a temperature is never below absolute zero". If other code can see and build the representation, it can break the rule, and it can come to depend on details that the module wants to change. An opaque type solves this: the code outside the module knows that the type exists and knows its operations, but it cannot see what the type is made of. In Rust, a field is private to its module by default, so a struct with a private field is opaque to the code outside.
mod temperature {
pub struct Celsius(f64); // the field is private to this module
impl Celsius {
pub fn from_degrees(c: f64) -> Option<Celsius> {
if c >= -273.15 { Some(Celsius(c)) } else { None }
}
pub fn fahrenheit(&self) -> f64 {
self.0 * 9.0 / 5.0 + 32.0
}
}
}
use temperature::Celsius;
fn main() {
let t = Celsius::from_degrees(100.0).unwrap();
println!("{}", t.fahrenheit());
println!("{}", Celsius::from_degrees(-300.0).is_none());
println!("{}", std::mem::size_of::<Celsius>());
// let bad = Celsius(-300.0); // error: the field is private
// println!("{}", t.0); // error: the field is private
}
212
true
8
main is outside the module temperature, so it cannot build a Celsius from a number or read its field. It must call from_degrees, which rejects a value below absolute zero, and fahrenheit. The type still has the size of one f64, so the hiding costs nothing at run time.
How it works
The representation is not in the interface. "In computer science, an opaque data type is a data type whose concrete data structure is not defined in an interface. This enforces information hiding, since its values can only be manipulated by calling subroutines that have access to the missing information"1. "A data type whose representation is visible is called transparent"1. The operations of the module form the interface of the type, so an opaque type is a common way to build an abstract data type1.
Incomplete types in C. C hides a struct by declaring it without its members. "An incomplete type is an object type that lacks sufficient information to determine the size of the objects of that type"2, and a structure type "of unknown content" is one kind2. "The only thing that the client can do with an object of such a type is to take its memory address, to produce an opaque pointer"1. The standard library works this way: its file functions take and return pointers to FILE, and "the concrete implementation of the type FILE is not specified"1.
Abstract types in ML modules. In OCaml, a signature lists the parts of a module that other code may use. "It can be used to hide some components of a structure (e.g. local function definitions) or export some components with a restricted type"3. A signature that declares type 'a queue without a definition "makes the queue type abstract (by not providing its actual representation as a concrete type)"3, and "This ensures that users of the Fifo module cannot violate data structure invariants that operations rely on"3.
Opaque return types. Rust and Swift let a function hide the concrete type of the value it returns and show only a trait or a protocol. In Rust, "Functions can use impl Trait to return an abstract return type. These types stand in for another concrete type where the caller may only use the methods declared by the specified Trait"4. In Swift, "A function or method that returns an opaque type hides its return value's type information"5. Swift describes this as "the reverse of a generic type"5: with a type parameter the caller chooses the type, but with impl Trait "the function chooses the return type, and the caller cannot choose the return type"4.
Opaque type aliases. Scala 3 can declare a type alias that is a plain alias inside its scope and an abstract type outside it. For opaque type Logarithm = Double, "The fact that Logarithm is the same as Double is only known in the scope where Logarithm is defined"6. Outside that scope, "To users of Logarithm it is not possible to discover that Logarithm is actually implemented as a Double"6. "Opaque type aliases provide type abstraction without any overhead"6.
Access control. In languages with classes, a private field gives a partly opaque type. "Some languages allow partially opaque types, e.g. a record which has some public fields, known and accessible to all clients, and some hidden fields which are not revealed in the interface. Such types play a fundamental role in object-oriented programming"1. In Rust, "By default, everything is private"7, with a few exceptions. In C#, a private member is one that "Only code declared in the same class or struct can access"8. In Go, "An identifier may be exported to permit access to it from another package"9, and only an identifier whose first letter is uppercase is exported9. In JavaScript, private class elements "cannot be legally referenced outside of the class", and "The privacy encapsulation of these class elements is enforced by JavaScript itself"10. See encapsulation and visibility.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Idiom | |
| C | Native | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript has private class members with. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Idiom | Kotlin has private and internal members, and a factory can return an interface while the class stays private. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query sees the columns of the tables it can read, and SQL has no user types with hidden parts. |
| Bash | Does not apply | Bash has no user-defined types. |
| PowerShell | Idiom | PowerShell uses .NET access control, as in C#. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types. |
| CSS | Does not apply | CSS has no types in this sense. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | a leading underscore marks a name as not public; nothing stops access |
| JavaScript | idiom | private class elements with #, or values that a closure keeps |
| TypeScript | idiom | # and private members; an exported interface without the class |
| Java | idiom | private fields; a public interface with a class that the package does not export |
| Kotlin | idiom | private and internal members; an exported interface without the class |
| C# | idiom | private and internal members; a public interface with an internal class |
| Go | idiom | identifiers that start with a lowercase letter are not exported from the package |
| Rust | native | items are private to their module by default; impl Trait hides a return type |
| C | native | a struct declared without its members is an incomplete type; code uses pointers to it |
| C++ | native | incomplete class types behind pointers, as in the pImpl technique; private members |
| Bash | n/a | Bash has no user-defined types |
| PowerShell | idiom | .NET access control, as in C# |
| SQL | n/a | a query sees the columns of the tables it can read; there are no user types with hidden parts |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types in this sense |
C, C++ and Rust can hide a type itself, so code outside the module does not know the size or the fields. Java, C#, Kotlin and Go hide the fields of a type, or let a factory return an interface so that the class stays unnamed. Python and JavaScript have no static types, so they hide data by convention, by private class elements, or in closures.
The example files show these differences. Python shows that a name with two underscores is renamed but can still be read. JavaScript shows a private # field and a value that a closure hides. Java shows a factory that returns an interface while the class stays private. C# shows an interface with a private nested class. Go shows a constructor that returns an interface. Rust shows impl Trait in return position. C shows an incomplete struct that the code uses only through pointers. C++ shows the pImpl technique.
class Account:
def __init__(self, balance: int) -> None:
self.__balance = balance # stored as _Account__balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("amount must be positive")
self.__balance += amount
@property
def balance(self) -> int:
return self.__balance
a = Account(10)
a.deposit(5)
print(a.balance)
try:
print(a.__balance)
except AttributeError as e:
print("AttributeError:", e)
print(sorted(vars(a)))
a._Account__balance = -100 # the convention does not stop this
print(a.balance)
15
AttributeError: 'Account' object has no attribute '__balance'
['_Account__balance']
-100
- Verdict: idiom. Python has no opaque types. A name with two leading underscores is renamed to
_Account__balance, soa.__balancefails outside the class. But the renamed attribute is still there, and any code can change it. A leading underscore is a promise between programmers, not a check.
#include <iostream>
#include <memory>
#include <string>
// The header: Widget holds only a pointer to an incomplete type.
class Widget {
public:
explicit Widget(std::string name);
~Widget();
void click();
std::string describe() const;
private:
struct Impl; // declared, not defined
std::unique_ptr<Impl> impl_;
};
// The source file: the members of Impl can change without a change to the header.
struct Widget::Impl {
std::string name;
int clicks = 0;
};
Widget::Widget(std::string name) : impl_(std::make_unique<Impl>()) {
impl_->name = std::move(name);
}
Widget::~Widget() = default; // Impl is complete here
void Widget::click() { impl_->clicks++; }
std::string Widget::describe() const {
return impl_->name + " " + std::to_string(impl_->clicks);
}
int main() {
Widget w("ok");
w.click();
w.click();
std::cout << w.describe() << "\n";
std::cout << (sizeof(Widget) == sizeof(void*)) << "\n";
}
ok 2
1
- Verdict: native.
Widgetholds astd::unique_ptrtoImpl, which the header declares but does not define, so the size ofWidgetis one pointer, and code that includes the header does not see the members. The destructor is defined afterImplis complete, becauseunique_ptrmust know the type to delete it.
import java.util.ArrayList;
import java.util.List;
public class Main {
// The public face of the type: callers see only these methods.
interface Stack {
void push(int x);
int pop();
boolean isEmpty();
}
// The representation is private to Main, so callers cannot name it.
private static final class ListStack implements Stack {
private final List<Integer> items = new ArrayList<>();
public void push(int x) { items.add(x); }
public int pop() { return items.remove(items.size() - 1); }
public boolean isEmpty() { return items.isEmpty(); }
}
static Stack newStack() {
return new ListStack();
}
public static void main(String[] args) {
Stack s = newStack();
s.push(1);
s.push(2);
System.out.println(s.pop() + " " + s.pop() + " " + s.isEmpty());
System.out.println(s instanceof Stack);
}
}
2 1 true
true
- Verdict: idiom. Java has no opaque type declaration. A factory returns the interface
Stack, and the classListStackand its list stay private. Code outside can change only through the interface, so the class could switch to an array without any change to the callers.
#include <stdio.h>
#include <stdlib.h>
/* The header: the struct has no members here, so it is incomplete. */
struct counter;
struct counter *counter_create(int start);
void counter_add(struct counter *c, int n);
int counter_value(const struct counter *c);
void counter_destroy(struct counter *c);
/* The user code: it can hold pointers, but not a struct counter. */
static void user(void) {
struct counter *c = counter_create(10);
counter_add(c, 5);
printf("%d\n", counter_value(c));
/* struct counter x; error: storage size of x is not known */
/* sizeof(struct counter) error: incomplete type */
counter_destroy(c);
}
/* The implementation: this part completes the type. */
struct counter {
int value;
int adds;
};
struct counter *counter_create(int start) {
struct counter *c = malloc(sizeof *c);
if (c == NULL) {
exit(1);
}
c->value = start;
c->adds = 0;
return c;
}
void counter_add(struct counter *c, int n) {
c->value += n;
c->adds++;
}
int counter_value(const struct counter *c) { return c->value; }
void counter_destroy(struct counter *c) { free(c); }
int main(void) {
user();
printf("%zu\n", sizeof(struct counter));
return 0;
}
15
8
- Verdict: native. In a real program the first part is a header and the last part is a separate source file. Before the definition,
struct counteris an incomplete type, sousercan pass pointers to it but cannot declare one, read its fields or take its size. The module allocates each counter and gives a destroy function.
using System;
using System.Collections.Generic;
var q = Queues.Create();
q.Enqueue("a");
q.Enqueue("b");
Console.WriteLine($"{q.Dequeue()} {q.Count}");
// var r = new Queues.ListQueue(); // error: ListQueue is private
public interface IQueue
{
void Enqueue(string item);
string Dequeue();
int Count { get; }
}
public static class Queues
{
public static IQueue Create() => new ListQueue();
private sealed class ListQueue : IQueue
{
private readonly List<string> _items = [];
public void Enqueue(string item) => _items.Add(item);
public string Dequeue()
{
var first = _items[0];
_items.RemoveAt(0);
return first;
}
public int Count => _items.Count;
}
}
a 1
- Verdict: idiom.
ListQueueis aprivatenested class, so onlyQueuescan name it or build it. Code outside gets anIQueuefromCreateand sees only the members of the interface. Aninternalclass gives the same hiding to code outside the assembly.
class Account {
#balance; // a private element
constructor(balance) {
this.#balance = balance;
}
deposit(amount) {
if (amount <= 0) throw new RangeError("amount must be positive");
this.#balance += amount;
}
get balance() {
return this.#balance;
}
}
const a = new Account(10);
a.deposit(5);
console.log(a.balance, Object.keys(a).length, JSON.stringify(a));
// a.#balance; // SyntaxError outside the class
function makeCounter() {
let count = 0; // only the returned functions can see this
return {
next: () => ++count,
reset: () => { count = 0; },
};
}
const c = makeCounter();
c.next();
console.log(c.next(), c.count, Object.keys(c).join(","));
15 0 {}
2 undefined next,reset
- Verdict: idiom. A
#field is private to the class body: other code cannot read it, and it does not show inObject.keysor in JSON. A closure gives the same hiding without a class: the variablecountlives in the scope ofmakeCounter, and only the two returned functions can reach it.
package main
import "fmt"
// Set is the exported face of the type.
type Set interface {
Add(s string)
Has(s string) bool
Len() int
}
// mapSet starts with a lowercase letter, so other packages cannot name it.
type mapSet struct {
items map[string]struct{}
}
func NewSet() Set {
return &mapSet{items: map[string]struct{}{}}
}
func (m *mapSet) Add(s string) { m.items[s] = struct{}{} }
func (m *mapSet) Has(s string) bool { _, ok := m.items[s]; return ok }
func (m *mapSet) Len() int { return len(m.items) }
func main() {
s := NewSet()
s.Add("a")
s.Add("a")
s.Add("b")
fmt.Println(s.Len(), s.Has("a"), s.Has("z"))
fmt.Printf("%T\n", s)
}
2 true false
*main.mapSet
- Verdict: idiom. Go hides by package:
mapSetand its fielditemsstart with a lowercase letter, so code in another package cannot name them, and must useNewSetand the methods ofSet. In this one-file example everything is in packagemain.%Tshows that the dynamic type is still there when the program runs.
// The caller sees only "some iterator of u32", not the adapter types.
fn evens(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0)
}
// A closure has a type with no name, so impl Trait is the way to return it.
fn adder(k: i32) -> impl Fn(i32) -> i32 {
move |x| x + k
}
fn main() {
let v: Vec<u32> = evens(10).collect();
println!("{:?}", v);
println!("{}", evens(100).map(|n| n * n).sum::<u32>());
let add5 = adder(5);
println!("{}", add5(10));
// let x: std::ops::Range<u32> = evens(10); // error: mismatched types
}
[0, 2, 4, 6, 8]
161700
15
- Verdict: native.
impl Iterator<Item = u32>hides the concrete type, aFilterover aRangewith a closure, so the caller can use only the methods ofIterator, and the function can change its body without a change to its signature. The value is not boxed. A closure has a type that no code can write, soimpl Fnis how a function returns one without a box.
Variations and related ideas
- Opaque pointers. "An opaque pointer is a special case of an opaque data type, a datatype that is declared to be a pointer to a record or data structure of some unspecified data type"1. Handles from an operating system are often opaque, for example the POSIX thread types1. "In some languages, such as Java, the only kind of opaque type provided is the opaque pointer"1.
- Opaque types versus boxed types. Swift contrasts opaque types with boxed protocol types: "Opaque types preserve type identity"5: "the compiler has access to the type information, but clients of the module don't"5. A boxed type, like a Rust trait object or a Java interface value, can hold values of different concrete types, and the code finds the type only when it runs5.
- Opaque types and abstract data types. "Opaque data types are frequently used to implement abstract data types"1. The type and its operations form the abstract data type, and the hidden representation lets the module change it.
- Friend modules. "The information which is missing in the interface may be declared in its implementation"1, or in a second interface that only some modules can see1. Rust
pub(crate)and C#internalshare hidden parts among the modules of one crate or one assembly78.
Pitfalls
- Privacy by convention. The Python tutorial says that private "instance variables that cannot be accessed except from inside an object" do not exist in Python11. A name with a leading underscore "should be treated as a non-public part of the API"11, and name mangling is "designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private"11. Do not use it for security.
- Exposed fields in a header. A C++ class with
privatemembers still puts those members in its header, and "any change to those implementation details requires recompilation of all users of the class"12. Use the pImpl technique, or a C-style incomplete type, when the layout must stay out of the header. - No values on the stack. In C, code outside the module cannot declare a variable of an incomplete struct type, because the size is unknown2. The module must allocate each value and give a destroy function, so the user must remember to call it. The C example shows this.
- One concrete type per function. For
impl Traitin return position, "Each possible return value from the function must resolve to the same concrete type"4. To return different types, return a trait object such asBox<dyn Trait>. - Zero-cost and checked are different. A Scala opaque alias or a Rust tuple struct has no cost at run time, but the check that a value obeys the rule happens only in the constructor. A module that gives a public field, or a function that converts from the raw type without a check, removes the protection.
Cost
An opaque type that the compiler sees through, such as a Scala opaque alias, a Rust private field or an impl Trait return, costs nothing at run time64. "impl Trait in return position allows a function to return an unboxed abstract type"4. An opaque pointer in C, or the pImpl technique in C++, costs an allocation for each value and an indirection for each access. In return, "changes to the implementation do not cause recompilation"12, and a library can change the representation without breaking code that it already linked with.
History
The C standard library uses an opaque FILE type for file streams, and the POSIX threads interface uses opaque types for threads, mutexes and condition variables1. OCaml hides types with module signatures3. Rust has impl Trait4, Swift has opaque return types with some5, and Scala 3 has opaque type aliases6.
References
- Opaque data type, Wikipedia, Introduction; Uses in various languages
- Type, C reference, cppreference.com, Incomplete types
- The module system, The OCaml Manual 5.3, 2 Signatures
- Impl trait, The Rust Reference, Abstract return types; Differences between generics and impl Trait in return position
- Opaque and Boxed Protocol Types, The Swift Programming Language, Introduction; Returning an Opaque Type
- Opaque Types, Scala 3 Book, Introduction; Opaque Types; Summary of Opaque Types
- Visibility and privacy, The Rust Reference, Default visibility
- Access Modifiers, C# programming guide, Introduction
- The Go Programming Language Specification, Exported identifiers
- Private elements, MDN Web Docs, Introduction
- Classes, The Python Tutorial 3.14, 9.6 Private Variables
- PImpl, C++ reference, cppreference.com, Introduction; Explanation
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag R3S50M Edit this page History Report an error Markdown