std.convert
The type conversion module currently provides conversion of values to String.
use std.convertConversion Rules
to_string formats a value according to its runtime form:
| Type | Output Form | Example |
|---|---|---|
Void | void | void |
Bool | true / false | true |
Int | Decimal | 42 |
Float | See below | 3.14 / 2.0 |
Char | The character itself | a |
String | Original content (without quotes) | hello |
List | [element, ...] | [1, 2, 3] |
Dict | {k: v, ...} | {a: 1} |
Tuple | (element, ...) | (1, hello) |
Array | [element, ...] | [1, 2] |
Range | start..end | 1..5 (the step is omitted when it is 1) |
Bytes | bytes[length] | bytes[3] |
Integral values of Float are given a decimal place (2.0 rather than 2) to distinguish Int from Float.
Function Overview
| Function | Signature |
|---|---|
to_string | (value) -> String |
int.to_string | (self) -> String |
float.to_string | (self) -> String |
bool.to_string | (self) -> String |
char.to_string | (self) -> String |
string.to_string | (self) -> String |
list.to_string | (self) -> String |
dict.to_string | (self) -> String |
tuple.to_string | (self) -> String |
set.to_string | (self) -> String |
range.to_string | (self) -> String |
Functions
to_string
to_string: (value) -> StringConverts any value to its string representation.
value— a value of any type
Returns: the formatted string. Returns "()" when the argument is missing.
use std.assert
use std.convert
main: () -> Void = {
assert(convert.to_string(42) == "42")
assert(convert.to_string(true) == "true")
assert(convert.to_string(false) == "false")
}Strings themselves are not quoted:
use std.assert
use std.convert
main: () -> Void = {
assert(convert.to_string("hi") == "hi")
}Composite types are expanded recursively (the format is not asserted, to avoid brittleness):
use std.assert
use std.convert
use std.string
main: () -> Void = {
s_list = convert.to_string([1, 2, 3])
assert(string.len(s_list) > 0)
s_dict = convert.to_string({})
assert(string.len(s_dict) > 0)
}Type-Specific Method Form
In addition to the general-purpose convert.to_string, the module exports the following type-bound functions of the same name, whose behavior is identical:
| Exported Name | Signature |
|---|---|
int.to_string | (self) -> String |
float.to_string | (self) -> String |
bool.to_string | (self) -> String |
char.to_string | (self) -> String |
string.to_string | (self) -> String |
list.to_string | (self) -> String |
dict.to_string | (self) -> String |
tuple.to_string | (self) -> String |
set.to_string | (self) -> String |
range.to_string | (self) -> String |
These bindings are used for runtime Stringable dispatch; in ordinary code, you can simply use convert.to_string.
The
Settype has been removed from the language layer;set.to_stringis retained as a compatibility placeholder.
Related
std.io— the internal formatting ofprint/printlnfollows the same set of rulesstd.string— string operations
