String
虽然 Move 没有内置类型来表示字符串,但它在标准库中有两种标准的字符串实现。 std::string 模块定义了 UTF-8 编码字符串的 String 类型和方法,第二个模块 std::ascii 提供了 ASCII String 类型及其方法。
Rooch执行环境自动将交易输入中的字节向量转换为字符串。所以很多情况下,Transaction Block中不需要构造String。
Rooch execution environment automatically converts bytevector into
Stringin transaction inputs. So in many cases, a String does not need to be constructed in the Transaction Block.
Strings are bytes
无论您使用哪种类型的字符串,重要的是要知道字符串只是字节。 string 和 ascii 模块提供的包装器就是:包装器。它们确实提供了安全检查和处理字符串的方法,但归根结底,它们只是字节向量。
module book::custom_string {
/// Anyone can implement a custom string-like type by wrapping a vector.
public struct MyString {
bytes: vector<u8>,
}
/// Implement a `from_bytes` function to convert a vector of bytes to a string.
public fun from_bytes(bytes: vector<u8>): MyString {
MyString { bytes }
}
/// Implement a `bytes` function to convert a string to a vector of bytes.
public fun bytes(self: &MyString): &vector<u8> {
&self.bytes
}
}
Working with UTF-8 Strings
虽然标准库中有两种类型的字符串,但 string 模块应被视为默认模块。它具有许多常见操作的本机实现,因此比在 Move 中完全实现的 ascii 模块更高效。
Definition
std::string模块中的String类型定义如下:
// File: move-stdlib/sources/string.move
/// A `String` holds a sequence of bytes which is guaranteed to be in utf8 format.
public struct String has copy, drop, store {
bytes: vector<u8>,
}