[−][src]Module lexpr::value
The Value enum, a dynamically typed way of representing any valid S-expression value.
Constructing S-Expressions
Lexpr provides a sexp!
macro to build lexpr::Value
objects with very natural S-expression syntax.
use lexpr::sexp; // The type of `john` is `lexpr::Value` let john = sexp!(( (name . "John Doe") (age . 43) (phones "+44 1234567" "+44 2345678") )); println!("first phone number: {}", john["phones"][0]); // Convert to a string of S-expression data and print it out println!("{}", john.to_string());
The Value::to_string()
function converts a lexpr::Value
into a
String
of S-expression text.
One neat thing about the sexp!
macro is that variables and
expressions can be interpolated directly into the S-expression
value as you are building it. The macro will check at compile time
that the value you are interpolating is able to be represented as
S-expression data.
To interpolate, use the comma (,
, also known as "unqote" in
Lisp). The interpolated expression must either be a single token,
or surrounded by round or curly braces.
let full_name = "John Doe"; let age_last_year = 42; // The type of `john` is `lexpr::Value` let john = sexp!(( (name . ,full_name) (age . ,(age_last_year + 1)) (phones ,{ format!("+44 {}", random_phone()) }) ));
A string of S-expression data can be parsed into a lexpr::Value
by the
lexpr::from_str
function. There is also
from_slice
for parsing from a byte slice &[u8]
and
from_reader
for parsing from any io::Read
like a file or
a TCP stream. For all these functions there also is a _custom
variant
which allows for specifying parser options, in case the input deviates from
the lexpr
default behavior.
use lexpr::{sexp, parse::Error, Value}; // Some S-expression input data as a &str. Maybe this comes from the user. let data = r#"( (name . "John Doe") (age . 43) (phones . ( "+44 1234567" "+44 2345678" )) )"#; // Parse the string of data into lexpr::Value. let v: Value = lexpr::from_str(data)?; // Access parts of the data by indexing with square brackets. println!("Please call {} at the number {}", v["name"], v["phones"][0]);
Enums
Value | Represents an S-expression value. |
Traits
Index | A type that can be used to index into a |