In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type, or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. Only one of the types can be in use at any one time, and a tag field explicitly indicates which type is in use. It can be thought of as a type that has several "cases", each of which should be handled correctly when that type is manipulated. This is critical in defining recursive datatypes, in which some component of a value may have the same type as that value, for example in defining a type for representing trees, where it is necessary to distinguish multi-node subtrees and leaves. Like ordinary unions, tagged unions can save storage by overlapping storage areas for each type, since only one is in use at a time.

Description

Tagged unions are most important in functional programming languages such as ML and Haskell, where they are called datatypes (see algebraic data type) and the compiler can verify that all cases of a tagged union are always handled, avoiding many types of errors. Compile-time checked sum types are also extensively used in Rust, where they are called enum. They can, however, be constructed in nearly any programming language, and are much safer than untagged unions, often simply called unions, which are similar but do not explicitly track which member of a union is currently in use.

Tagged unions are often accompanied by the concept of a constructor, which is similar but not the same as a constructor for a class. A constructor is a function or an expression that produces a value of the tagged union type, given a tag and a value of the corresponding type.

Mathematically, tagged unions correspond to disjoint or discriminated unions, usually written using +. Given an element of a disjoint union , it is possible to determine whether it came from or . If an element lies in both, there will be two effectively distinct copies of the value in , one from and one from .

In type theory, a tagged union is called a sum type. Sum types are the dual of product types. Notations vary, but usually the sum type comes with two introduction forms (injections) and . The elimination form is case analysis, known as pattern matching in ML-style languages: if has type and and have type under the assumptions and respectively, then the term has type . The sum type corresponds to intuitionistic logical disjunction under the Curry–Howard correspondence.

An enumerated type can be seen as a degenerate case: a tagged union of unit types. It corresponds to a set of nullary constructors and may be implemented as a simple tag variable, since it holds no additional data besides the value of the tag.

Many programming techniques and data structures, including rope, lazy evaluation, class hierarchy (see below), arbitrary-precision arithmetic, CDR coding, the indirection bit, and other kinds of tagged pointers, are usually implemented using some sort of tagged union.

A tagged union can be seen as the simplest kind of self-describing data format. The tag of the tagged union can be seen as the simplest kind of metadata.

In languages with flow-sensitive typing, tagged unions can be implemented by a combination of union types and record types.[1]

Advantages and disadvantages

The primary advantage of a tagged union over an untagged union is that all accesses are safe, and the compiler can even check that all cases are handled. Untagged unions depend on program logic to correctly identify the currently active field, which may result in strange behavior and hard-to-find bugs if that logic fails.

The primary advantage of a tagged union over a simple record containing a field for each type is that it saves storage by overlapping storage for all the types. Some implementations reserve enough storage for the largest type, while others dynamically adjust the size of a tagged union value as needed. When the value is immutable, it is simple to allocate just as much storage as is needed.

The main disadvantage of tagged unions is that the tag occupies space. Since there are usually a small number of alternatives, the tag can often be squeezed into 2 or 3 bits wherever space can be found, but sometimes even these bits are not available. In this case, a helpful alternative may be folded, computed or encoded tags, where the tag value is dynamically computed from the contents of the union field. Common examples are the use of reserved values, where, for example, a function returning a positive number may return -1 to indicate failure, and sentinel values, most often used in tagged pointers.

Sometimes, untagged unions are used to perform bit-level conversions between types, or type punning. Tagged unions are not intended for this purpose; typically a new value is assigned whenever the tag is changed.

Many languages support, to some extent, a universal data type, which is a type that includes every value of every other type, and often a way is provided to test the actual type of a value of the universal type. These are sometimes referred to as variants. While universal data types are comparable to tagged unions in their formal definition, typical tagged unions include a relatively small number of cases, and these cases form different ways of expressing a single coherent concept, such as a data structure node or instruction. Also, there is an expectation that every possible case of a tagged union will be dealt with when it is used. The values of a universal data type are not related and there is no feasible way to deal with them all.

Like option types and exception handling, tagged unions are sometimes used to handle the occurrence of exceptional results. Often these tags are folded into the type as reserved values, and their occurrence is not consistently checked: this is a fairly common source of programming errors. This use of tagged unions can be formalized as a monad with the following functions:

where and are the constructors of the union type, and are valid result types and is the type of error conditions. Alternately, the same monad may be described by and two additional functions, and :

Examples

A binary tree of integers in ML can be expressed using a data type similar to the following:

datatype tree = Leaf
              | Node of (int * tree * tree)

This is a tagged union with two cases: one, the leaf, is used to terminate a path of the tree, and functions much like a null value would in imperative languages. The other branch holds a node, which contains an integer and a left and right subtree. Leaf and Node are the constructors, which are used to create a given tree, such as:

Node(5, Node(1, Leaf, Leaf), Node(3, Leaf, Node(4, Leaf, Leaf)))

which corresponds to this tree:

The tree produced by the above constructors

It then becomes trivial to write a type-safe function that, for example, counts the number of nodes in the tree:

fun countNodes(Leaf) = 0
  | countNodes(Node(int, left, right)) =
      1 + countNodes(left) + countNodes(right)

Language support

ALGOL 68

In ALGOL 68, tagged unions are called united modes, the tag is implicit, and the case construct is used to determine which field is tagged:

mode node = union (real, int, compl, string);

Usage example for union case of node:

node n := "1234";
 
case n in
  (real r):   print(("real:", r)),
  (int i):    print(("int:", i)),
  (compl c):  print(("compl:", c)),
  (string s): print(("string:", s))
  out         print(("?:", n))
esac

In ALGOL 68, a union can be automatically coerced into a wider union, for example if all its constituents can be handled by the union parameter of print, a union can simply be passed to print as in the out case above.

Ada

In Ada, these are called "discriminated types".

type Shape_Kind is (Square, Rectangle, Circle);
type Shape (Kind : Shape_Kind) is record
   Center_X : Integer;
   Center_Y : Integer;
   case Kind is
      when Square =>
         Side : Integer;
      when Rectangle =>
         Width, Height : Integer;
      when Circle =>
         Radius : Integer;
   end case;
end record;

-- Any attempt to access a member which existence depends
-- on a certain value of the discriminant, while the
-- discriminant is not the expected one, raises an error.

C++

While C only provides union, an untagged union type, C++ offers a class std::variant<Ts...> (since C++17), but rather than being a core language feature like ;\n\nPet p1 = Cat(\"Whiskers\");\nPet p2 = Dog(\"Rex\");\n"}}'>

import std;

using std::string;
using std::variant;

struct Cat {
    string name;
};

struct Dog {
    string name;
};

struct Bird {
    string name;
};

using Pet = variant<Cat, Dog, Bird>;

Pet p1 = Cat("Whiskers");
Pet p2 = Dog("Rex");

The "overload pattern" is a common design pattern that implements algebraic pattern matching using variadic template inheritance.[2]

// Helper type for visitor
template <typename... Ts>
struct Overload : public Ts... {
    using Ts::operator()...;
}

// Deduction guide
template <typename... Ts>
Overload(Ts...) -> Overload<Ts...>;

Then, the std::visit() function may be used to call each respective case, with each case handled by a lambda:[3]

using Value = variant<int, double, string>;

Value v = 3.14;

// prints "double: 3.14"
std::visit(
    Overload {
        [](int i) -> void { std::println("int: {}", i); },
        [](double d) -> void { std::println("double: {}", d); },
        [](const string& s) -> void { std::println("string: {}", s); }
    },
    v
);

Additionally, std::visit() may be made to return a type:

Pet p = Bird("Polly");

string name = std::visit(
    Overload {
        [](const Cat& c) -> string { return c.name; },
        [](const Dog& d) -> string { return d.name; },
        [](const Bird& b) -> string { return b.name; }
    },
    p
);

// Prints "Pet name: Polly"
std::println("Pet name: {}", name);

Since C++26, visit() may be used as method of std::variant<Ts...>:

Pet p = Bird("Polly");

Overload visitor(
    [](const Cat& c) -> string { return c.name; },
    [](const Dog& d) -> string { return d.name; },
    [](const Bird& b) -> string { return b.name; }
);

// Prints "Pet name: Polly"
std::println("Pet name: {}", p.visit(visitor));

The result type for error handling (like std::result::Result<T, E> in Rust), was introduced to C++23 as std::expected<T, E>.