Strings
Move does not have a native type for strings, but it has a handy wrapper! Sui supports String
type as a transaction argument (encoded as vector<u8>
on the client).
module examples::strings {
use std::string::String;
/// A dummy Object that holds a String type
public struct Name has key, store {
id: UID,
/// Here it is - the String type
name: String
}
/// Create a name Object by passing raw bytes
public fun mint_name(name: String, ctx: &mut TxContext): Name {
Name { id: object::new(ctx), name }
}
}
String operations
To create a string from a vector of bytes, use string::utf8
:
module examples::string_operations {
use std::string::String;
/// Constants can't be Strings; and they're not public.
const HELLO_WORLD: vector<u8> = b"Hello, World!";
/// But a function can pack a string and make it accessible.
/// Note: `string::utf8` fails if the string is not valid UTF-8.
public fun hello_world(): String {
HELLO_WORLD.to_string()
}
/// Checks if it's a valid UTF-8 String and returns an option
public fun new_string_safe(bytes: vector<u8>): Option<String> {
bytes.try_to_string()
}
}