Move does not have string literals like in other languages, so code like this, which you might expect to work:
module example::foo {
use std::string::String;
public fun bar() {
let s: String = "hello";
}
}
Will produce the following error:
error[E01001]: invalid character
┌─ ./sources/foo.move:21:25
│
21 │ let s: String = "hello";
│ ^ Invalid character: '"'
Failed to build Move modules: Compilation error.
Instead of string literals, Move has two other kinds of literals: byte-string literals and hex-string literals, which look similar to strings, but prefixed with b
and x
respectively. Both these literals produce vector<u8>
:
module example::foo {
public fun bar() {
assert!(b"hello" == vector[104, 101, 108, 108, 111], 0);
assert!(x"c0de" == vector[0xc0, 0xde], 0);
}
}
The string
and ascii
modules offer ways to convert these literals to String
types:
module example::foo {
use std::ascii::{Self, String as ASCIIString};
use std::string::{Self, String as UTF8String};
public fun bar() {
let hello_utf8: UTF8String = string::utf8(b"Hello \xF0\x9F\x98\x8A!");
let hello_ascii: ASCIIString = ascii::string(b"Hello :)!");
}
}