Conceptcore
Unit type
Also called unit, (), Unit, void, Void, None, NoneType, empty tuple, 0-tuple, struct{}, std::monostate.
The unit type has exactly one value, so a value of it carries no information. A function that runs only for its side effects returns it, as () in Rust or None in Python.
- Applies to
- core-languages
Idea
Some functions run only for what they do: they print a line, write a file or change a variable. They have no result to give back. In a language where each function call is an expression with a type, such a function still needs a result type. The unit type is that type. It has exactly one value, so the value says nothing, and the program can ignore it. Rust and Haskell write the type and its value as (), Kotlin calls it Unit, and Python uses None.
# None is the only value of its type.
print(type(None).__name__, None is None, type(None)() is None)
def log(msg: str) -> None:
print("log:", msg)
result = log("start")
print(result, result is None)
# A function without a return statement returns None.
def nothing():
pass
print(nothing() is None, [nothing() for _ in range(3)])
# A dict with None values works as a set that keeps the order of insertion.
seen = dict.fromkeys(["b", "a", "b"])
print(seen, list(seen))
NoneType True True
log: start
None True
True [None, None, None]
{'b': None, 'a': None} ['b', 'a']
NoneType has one value, and even a call to the type gives back the same None. log has the annotation -> None, and its call still has a value that the program can store and test. A function without a return statement returns None too, so a list of three calls holds three None values. In the last lines, the values of the dictionary are all None, so only the keys carry information, and the dictionary works as an ordered set.
How it works
One value, no information. "In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information)"1. "One may also regard the unit type as the type of 0-tuples, i.e. the product of no types"1. The unit type is not the empty type: the empty type has no values at all. See bottom type.
What it is for. "Several computer programming languages provide a unit type to specify the result type of a function with the sole purpose of causing a side effect, and the argument type of a function that does not require arguments"1. In Rust, "The () type has exactly one value (), and is used when there is no other meaningful value that could be returned", and "functions without a -> ... implicitly have return type ()"2. In Haskell, "The unit datatype () has one non-⊥ member, the nullary constructor ()"3.
The names in each language. Kotlin has "The type with only one value: the Unit object. This type corresponds to the void type in Java"4. In Python, None "is the sole instance of the NoneType type"5. Go has no named unit type, but the empty struct struct{} has one value, and "A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero"6. The C++ library has std::monostate, a "Unit type intended for use as a well-behaved empty alternative in std::variant"7. Java has the class Void, which "is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void"8. Its only value is null, and code uses it as a type argument, as in CompletableFuture<Void>.
Why expression languages need it. In Rust, ML and Haskell, a block, an if and a function call are expressions, and each expression has a type. A block that ends with a statement still has a value. In Rust, "The semicolon ; can be used to discard the result of an expression at the end of a block, making the expression (and thus the block) evaluate to ()"2. Generic code needs the unit type too: a generic function that returns T works for a function without a result only if T can be the unit type. Thus Result<(), E> in Rust is the result of an operation that can fail but has no value when it succeeds, and HashMap<K, ()> is a set. See statements and expressions.
void is not a full unit type. C, C++, Java and C# use void for a function without a result. In C++, void is a "type with an empty set of values. It is an incomplete type that cannot be completed (consequently, objects of type void are disallowed)"9. Wikipedia says that void "is semantically similar to an implicit unit type, not a zero or bottom type", but "Unlike a real unit type which is a singleton, the void type lacks a way to represent its value"10. Two limits follow. Wikipedia says that "the void type cannot be the type of an argument in C", so f(g()) does not compile when g returns void, and "the void type is special and can never be stored in a record type"1. In C#, void is used "as the return type of a method or a local function to specify that the method doesn't return a value"11, so a delegate for such a method is an Action, not a Func. void * in C and C++ is another idea: it is a pointer to data of an unknown type, "but this is an unrelated notion"10.
void in TypeScript. In TypeScript, void "represents the return value of functions which" do not return a value12. A function type with a void result accepts a function that returns a value: "when implemented, can return any other value, but it will be ignored"12. JavaScript itself returns undefined from such a function.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Idiom | |
| TypeScript | Native | TypeScript has void for the result of a function that returns no value, and undefined and null are types with one value each. A function type with a void result accepts a function that returns a value, and the caller ignores that value. No example file exists. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | Unit is an object, so it is a type with one value, and a function without a declared result type returns Unit. Unit can be a type argument, as in a function type such as () -> Unit. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A stored procedure can run only for its effect and give no result value, while a function must return a value. NULL marks an absent value, which is a different idea. No example file exists. |
| Bash | Idiom | A function always gives an exit status, and it passes data by its output, not by a return value. A function that runs only for its effect returns the status 0 and prints nothing. No example file exists. |
| PowerShell | Idiom | A cast to [void] or a pipe to Out-Null discards a value. A function with no output gives no value, and a variable that stores such a result holds $null. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types of values and no functions. |
| CSS | Does not apply | CSS has no unit type. Its units, such as px and em, are units of measure for lengths, which is a different idea. |
| Regular expressions | Does not apply | A regular expression has no values and no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | None, the one value of NoneType; -> None in annotations |
| JavaScript | idiom | undefined is the result of a function without return; null also has one value |
| TypeScript | native | void for a result that the caller ignores; undefined as a type with one value |
| Java | stdlib | void for methods; the class Void, whose only value is null, as a type argument |
| Kotlin | native | Unit, a singleton object; a function without a result type returns Unit |
| C# | stdlib | void for methods; Action instead of Func; the empty ValueTuple as a unit value |
| Go | idiom | struct{} with the one value struct{}{}, of size zero; a function can have no result |
| Rust | native | (), the empty tuple; a block that ends with ; has the value () |
| C | idiom | void for a function without a result or without parameters; no unit value |
| C++ | native | void as in C; std::monostate and an empty struct are unit types |
| Bash | idiom | a function always gives an exit status; output, not a return value, carries data |
| PowerShell | idiom | [void] discards a value; a function with no output returns nothing, which is $null when stored |
| SQL | idiom | a procedure has no result value; NULL stands for an absent value |
| Regex | n/a | a pattern has no values |
| HTML | n/a | HTML has no types of values |
| CSS | n/a | CSS has no unit type; its units, such as px, are units of measure |
The table has the verdict "stdlib" for Java and C#, because void covers the result of a method but is not a type that generic code can use, so these languages use library types such as Void, Action and ValueTuple. Rust, Kotlin, Python and C++ with std::monostate have a real unit type. Go and C have no named unit type.
The example files show these differences. Python shows that list.sort returns None and that None is falsy. JavaScript shows that a function without return gives undefined and that the void operator gives undefined too. Java uses Void as a type argument and shows that Runnable and Supplier are two interfaces. C# uses Action for a method without a result and shows the empty ValueTuple. Go uses map[string]struct{} as a set and a channel of struct{} as a signal. Rust shows that () has the size 0, that ; gives (), and uses HashMap<K, ()> and Result<(), E>. C shows void functions and the (void) cast that discards a result. C++ shows std::monostate in a std::variant and std::is_void.
from typing import get_type_hints
# A method that changes the list in place returns None.
items = [3, 1, 2]
result = items.sort()
print(result, items)
print(sorted([3, 1, 2]))
# None is falsy, but it is not equal to 0 or False.
print(bool(None), None == 0, None == False)
# get gives None for a missing key and for a key whose value is None.
d = {"a": None}
print(d.get("a"), d.get("b"), "a" in d, "b" in d)
def f() -> None:
pass
print(get_type_hints(f))
None [1, 2, 3]
[1, 2, 3]
False False False
None None True False
{'return': <class 'NoneType'>}
- Verdict: native.
Noneis the one value ofNoneType, and a function without a result returns it.list.sortchanges the list and returnsNone, soresultholdsNone, andsortedis the function that gives a sorted copy.Noneis falsy but not equal to0orFalse. BecauseNonealso marks a missing value,d.get("a")andd.get("b")both giveNone, and onlyintells the two cases apart. In an annotation,Nonestands forNoneType.
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
struct Empty {};
int main() {
// std::monostate gives a variant an empty first alternative.
std::variant<std::monostate, int, std::string> v;
std::cout << v.index() << " " << std::holds_alternative<std::monostate>(v) << "\n";
v = 7;
std::cout << v.index() << "\n";
std::cout << (std::monostate{} == std::monostate{}) << "\n";
// void is an incomplete type, so no object can have it.
std::cout << std::is_void_v<void> << " " << std::is_void_v<std::monostate> << "\n";
// An empty struct has one value, but a complete object still takes one byte.
std::cout << sizeof(Empty) << " " << sizeof(std::monostate) << "\n";
}
0 1
1
1
1 0
1 1
- Verdict: native.
voidworks as in C, andstd::is_void_vtells it apart from other types.std::monostateis a real unit type: it has one value, all its values are equal, and a defaultstd::variantholds it, soindex()is 0. An empty struct such asEmptyis also a unit type, but each complete object has the size 1, so that two objects have two addresses.
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
public class Main {
static void greet(String name) {
System.out.println("hello " + name);
}
// A generic method needs a type argument for "no result", so Void stands in.
static <T> T timed(String label, Supplier<T> body) {
T result = body.get();
System.out.println(label + " done");
return result;
}
public static void main(String[] args) {
Integer n = timed("sum", () -> 1 + 2);
System.out.println(n);
Void v = timed("greet", () -> {
greet("Ann");
return null;
});
System.out.println(v);
// Runnable has a void method, and Supplier has a result.
Runnable r = () -> greet("Bo");
r.run();
CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {});
System.out.println(f.join());
System.out.println(void.class + " " + Void.class.getName() + " " + Void.TYPE);
}
}
sum done
3
hello Ann
greet done
null
hello Bo
null
void java.lang.Void void
- Verdict: stdlib.
voidmarks a method without a result, butvoidcannot be a type argument, soSupplier<void>does not compile. Code usesVoidinstead, and becauseVoidhas no instances, the only value it can hold isnull. That is why the lambda forgreetends withreturn null, and whyCompletableFuture<Void>givesnull.RunnableandSupplierare two interfaces for the cases with and without a result.Void.TYPEis theClassobject for the keywordvoid.
#include <stdio.h>
static int count = 0;
/* A function without a result: it runs for its side effect. */
static void bump(int by) {
count += by;
}
/* (void) in the parameter list means that the function takes no arguments. */
static int get(void) {
return count;
}
int main(void) {
bump(2);
bump(3);
printf("%d\n", get());
/* A cast to void discards a result on purpose. */
(void)printf("printed\n");
/* void * is a different idea: a pointer to data of an unknown type. */
int x = 42;
void *p = &x;
printf("%d\n", *(int *)p);
return 0;
}
5
printed
42
- Verdict: idiom. C has no unit value.
voidas a result type means that a call gives no value, sobump(2)can only be a statement, andvoidin a parameter list means no parameters. The cast(void)discards the result ofprintfand tells the reader that this is on purpose.void *is a pointer to data of an unknown type, which is not a unit type.
using System;
int n = Run.Timed("sum", () => 1 + 2);
Console.WriteLine(n);
Run.Timed("greet", () => Run.Greet("Ann"));
// The empty ValueTuple has one value, so it can act as a unit type.
Func<ValueTuple> unit = () =>
{
Run.Greet("Bo");
return ValueTuple.Create();
};
ValueTuple u = unit();
Console.WriteLine($"{u} {u.Equals(default(ValueTuple))} {typeof(void)}");
static class Run
{
public static void Greet(string name) => Console.WriteLine($"hello {name}");
public static T Timed<T>(string label, Func<T> body)
{
T result = body();
Console.WriteLine($"{label} done");
return result;
}
// A method without a result needs a second overload with Action.
public static void Timed(string label, Action body)
{
body();
Console.WriteLine($"{label} done");
}
}
sum done
3
hello Ann
greet done
hello Bo
() True System.Void
- Verdict: stdlib.
voidmarks a method without a result, butFunc<void>does not exist, so the library hasActionfor delegates without a result andFuncfor delegates with one.Timedneeds two overloads for this reason. The emptyValueTuplehas one value, which prints as(), so code can return it from aFuncwhen it needs a unit value.typeof(void)isSystem.Void.
function log(msg) {
console.log("log:", msg);
}
const r = log("start");
console.log(r, typeof r, r === undefined);
// The void operator evaluates an expression and gives undefined.
console.log(void 0, void log("again"));
// An arrow function with a block body and no return gives undefined.
const f = () => {
1 + 1;
};
const g = () => 1 + 1;
console.log(f(), g());
// forEach runs a callback for its effect and returns undefined.
console.log([1, 2].forEach((x) => x * 2), [1, 2].map((x) => x * 2));
log: start
undefined undefined true
log: again
undefined undefined
undefined 2
undefined [ 2, 4 ]
- Verdict: idiom. JavaScript has no unit type by name, but a function without
returngivesundefined, andundefinedis the only value of its type. Thevoidoperator evaluates its operand, solog("again")prints its line, and then givesundefined. An arrow function with braces needsreturn, sofgivesundefinedandggives2.forEachreturnsundefined, andmapreturns an array.
package main
import (
"fmt"
"unsafe"
)
func main() {
// struct{} has one value, struct{}{}, and it needs no storage.
var u struct{}
fmt.Println(unsafe.Sizeof(u), u == struct{}{})
// A map to struct{} is a set: only the keys carry information.
seen := map[string]struct{}{}
for _, w := range []string{"b", "a", "b"} {
seen[w] = struct{}{}
}
_, ok := seen["a"]
fmt.Println(len(seen), ok)
// A channel of struct{} carries only the fact that something happened.
done := make(chan struct{})
go func() {
fmt.Println("work")
close(done)
}()
<-done
fmt.Println("done")
// A function can have no result at all, so its call is not a value.
f := func() { fmt.Println("no result") }
f()
fmt.Printf("%T\n", f)
}
0 true
2 true
work
done
no result
func()
- Verdict: idiom. Go has no named unit type, but the empty struct
struct{}has one value and the size 0. Amap[string]struct{}is the usual set, and achan struct{}signals an event without data. A function can have no result, as the typefunc()shows, and a call to it cannot appear where a value is needed.
use std::collections::HashMap;
use std::mem::size_of;
fn greet(name: &str) {
println!("hello {name}");
}
fn check_positive(s: &str) -> Result<(), String> {
let n: i32 = s.parse().map_err(|e| format!("{e}"))?;
if n > 0 {
Ok(())
} else {
Err(format!("{n} is not positive"))
}
}
fn main() {
let r: () = greet("Ann");
println!("{:?} {} {}", r, size_of::<()>(), size_of::<((), ())>());
// A semicolon at the end of a block makes the block evaluate to ().
let a = {
let x = 1 + 2;
x
};
let b = {
let _x = 1 + 2;
};
println!("{a} {b:?}");
let mut seen: HashMap<&str, ()> = HashMap::new();
for w in ["b", "a", "b"] {
seen.insert(w, ());
}
println!("{} {}", seen.len(), seen.contains_key("a"));
println!("{:?} {:?}", check_positive("5"), check_positive("-1"));
}
hello Ann
() 0 0
3 ()
2 true
Ok(()) Err("-1 is not positive")
- Verdict: native.
greethas no->, so it returns(), and the program can store that value.()and a tuple of units have the size 0. The block foraends withx, so its value is 3, and the block forbends with a statement, so its value is().HashMap<&str, ()>keeps only the keys, which is howHashSetis built.Result<(), String>is the result of a check that can fail but has no value when it succeeds.
Variations and related ideas
- Unit versus bottom. The unit type has one value, and the bottom type has none. A function that returns unit returns normally. A function that returns the bottom type does not return.
- Unit versus null.
Nonein Python andnullin Java are also the values that stand for a missing value. The unit type itself has no notion of absence, but in these languages one value does both jobs. See null references. - Empty tuple and empty struct. The unit type is the product of no types, so Rust writes it as the empty tuple, and Go and C++ can use an empty struct. See tuple and composite type.
- A set as a map to unit.
HashMap<K, ()>in Rust andmap[K]struct{}in Go keep only the keys. See set.
Pitfalls
- A method that changes in place returns unit. In Python,
x = items.sort()setsxtoNone. The documentation says that, "To remind users that it operates by side-effect, it returns None"13. Usesorted(items)for a sorted copy. - Generic code that cannot use void.
Func<void>does not exist in C#, andFunction<String, void>does not compile in Java. Write two overloads, one withActionand one withFunc, or useVoidand returnnullin Java. - A TypeScript callback that returns a value. Because a
voidfunction type accepts a function that returns a value12,forEachacceptspushas a callback, and the result ofpushis dropped. Do not use the result of a call whose type isvoid. - A void result in C. A call to a
voidfunction cannot be an argument or an operand, because "the void type cannot be the type of an argument in C"1. - Unit is not a missing value. In Python and JavaScript,
Noneandundefinedare both the result of a function without a result and a marker for a missing value. A dictionary lookup that returnsNonecan mean "absent" or "present with the value None".
Cost
A value of the unit type carries no information, so it needs no storage and no work. In Rust, () and a struct of units have the size 0, and in Go, a value of size zero can share its address with another one6. A HashMap<K, ()> stores only the keys, so it costs the same as a set. In Python, None is one object that all code shares, and a dict with None values still stores a pointer for each value. In Java, Void costs nothing, because its only value is null.
History
The void type is older than the name unit in most languages. ALGOL 68, which IFIP Working Group 2.1 adopted "On 20 December 1968"14, lists VOID among its reserved words14. Wikipedia says that the void type appears in "curly bracket programming languages derived from C and ALGOL 68"10. "In the earliest versions of C, functions with no specific result defaulted to a return type of int"10, and void came later. The functional languages took the unit type from type theory: "In Haskell, Rust, and Elm, the unit type is called () and its only value is also ()"1, and "In ML descendants (including OCaml, Standard ML, and F#), the type is called unit but the value is written as ()"1.
References
- Unit type, Wikipedia, Introduction; In programming languages; Void type as unit type
- Primitive Type unit, The Rust Standard Library, Description
- Haskell 2010 Language Report, Chapter 6, Predefined Types and Classes, 6.1.5 The Unit Datatype
- Unit, Kotlin Standard Library API reference, Description
- Built-in Constants, Python 3.14 documentation, None
- The Go Programming Language Specification, Size and alignment guarantees
- std::monostate, C++ reference, cppreference.com, Description
- Java SE 25 API, Class Void, Description
- Fundamental types, C++ reference, cppreference.com, void type
- Void type, Wikipedia, Introduction; In C and C++
- void, C# language reference, Introduction
- More on Functions, The TypeScript Handbook, Other Types to Know About, void; Return type void
- Built-in Types, Python 3.14 documentation, Mutable Sequence Types, sequence.reverse()
- ALGOL 68, Wikipedia, History; Bold symbols and reserved words
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 66F7BD Edit this page History Report an error Markdown