Julia DISCUSSION

What is a Symbol in Julia and when should I use :name instead of a string?

Started by andreatigor Julia Symbolinterned stringsmetaprogrammingdictionary keysSymbol vs String
4 replies 248 views 5 participants
Latest activity · 30 Sep 2026

What is a Symbol in Julia and when should I use :name instead of a string?

andreatigor Julia Forum
#1

I keep meeting values like :red, :x and :Float64 in Julia code: as plot options, as DataFrame column names and inside macros. They look like strings without the closing quote, and typeof(:x) says Symbol.

What is a Symbol actually for, how is it different from the string "x", and how do I decide which of the two to use for things like option names or dictionary keys?

Community replies 4

Re: What is a Symbol in Julia and when should I use :name instead of a string?

#2

A Symbol is an interned name. The language uses it to represent identifiers when code is handled as data: the expression :(a + b) is an Expr whose arguments are the symbols :+, :a and :b. That is the original purpose: a macro or eval needs a way to say "the variable called a" as opposed to "the text a". eval(:a) looks up the variable a, while eval("a") just returns the string.

Re: What is a Symbol in Julia and when should I use :name instead of a string?

#3

Interned means there is exactly one object for each distinct name, so comparing two symbols is an identity check, the same cost as comparing two pointers, no matter how long the name is. String comparison has to look at the contents. That makes symbols a good fit for a small fixed set of labels that are compared or used as keys very often: option values such as :left and :right, keyword names, column names, states of a state machine.

You can convert both ways with Symbol("x") and String(:x).

Re: What is a Symbol in Julia and when should I use :name instead of a string?

#4

What a Symbol is not: a text type. There is no indexing, no length, no concatenation with *, no uppercase; you convert to String first. So data that arrives from outside, such as file contents, user input or serial messages, belongs in String. Symbols are for names chosen by the programmer.

Also avoid generating large numbers of distinct symbols from data, since each new name is added to a global table.

Re: What is a Symbol in Julia and when should I use :name instead of a string?

#5

Two places where the distinction is visible in everyday code. Keyword arguments and named tuples are keyed by symbols: nt = (gain = 2, offset = 0.5) has keys(nt) == (:gain, :offset), and nt[:gain] returns 2.

And with a Dict, d[:x] and d["x"] are different keys, so a dictionary filled with string keys from a parsed file will not find :x. Pick one key type per dictionary and state it, as in Dict{Symbol,Float64}(); storing a key of the wrong type then throws an error instead of silently creating a second entry.

TEP COMMUNITY