HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

What is Cons()?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whatconsstackoverflow

Problem

The Rust tutorial example of a linked list is:

enum List {
    Cons(u32, Box),
    Nil
}


What exactly is the Cons() struct? (It is a struct right?) I can't find any documentation on this anywhere.

Solution

Cons does not have a special meaning in Rust. It is only the name that the author of the tutorial chose to call that variant of the enum. The same List could have been defined as:

enum List {
    Pair(u32, Box),
    Nil
}


The name cons comes from the Lisp family of programming languages where pairs (nodes of linked lists) are used as the fundamental building blocks of data structures. Here is one way to create the 1,2,3 list in Common Lisp:

(cons 1 (cons 2 (cons 3 nil)))


cons is a shorthand of construct by which Lisp programmers mean to allocate memory. Programs that allocate a lot of memory are said to be consing too much.
Sources

  • cons - wikipedia



  • Marijn Haverbeke's presentation on JS performance

Code Snippets

enum List {
    Pair(u32, Box<List>),
    Nil
}
(cons 1 (cons 2 (cons 3 nil)))

Context

Stack Overflow Q#23311773, score: 100

Revisions (0)

No revisions yet.