将字符串内存转换为字符串调用数据?
Converting string memory to string calldata?
想知道是否可以在字符串内存和字符串调用数据之间进行转换,以便使用仅适用于字符串调用数据的字符串 [start : end] 形式的索引。这个功能似乎有效:
function splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {
if (startPos > int(length(sourcestring))) return "";
int start = startPos -1;
int end = startPos + (numchars -1);
string memory retval = string(source[uint(start) : uint(end)]);
return retval;
}
但是如果我将参数 source
更改为字符串内存,则会出现错误
string memory retval = string(source([uint(start) : uint(end)])
因为显然 sourcestring[start : end]
获取子字符串的形式适用于 calldata
字符串而不适用于 memory
字符串,并且没有明显的方法将 string memory
转换为 string calldata
.
有什么办法吗?
可能不会,因为 calldata 用于在进行外部交易时提供的数据。与存储相比,用途截然不同。
呼叫数据是只读的。您可以将 calldata 变量解码到内存中,但反之则不行。
不幸的是,数组切片仅针对 calldata 实现。对于内存和存储,它有点复杂,还没有实现(见问题#7423)。
你的解决方法是一个一个地复制字符,这实际上是编译器在幕后所做的,因为你试图 return 来自 [=17= 的切片] 函数(将切片具体化为数组)。
想知道是否可以在字符串内存和字符串调用数据之间进行转换,以便使用仅适用于字符串调用数据的字符串 [start : end] 形式的索引。这个功能似乎有效:
function splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {
if (startPos > int(length(sourcestring))) return "";
int start = startPos -1;
int end = startPos + (numchars -1);
string memory retval = string(source[uint(start) : uint(end)]);
return retval;
}
但是如果我将参数 source
更改为字符串内存,则会出现错误
string memory retval = string(source([uint(start) : uint(end)])
因为显然 sourcestring[start : end]
获取子字符串的形式适用于 calldata
字符串而不适用于 memory
字符串,并且没有明显的方法将 string memory
转换为 string calldata
.
有什么办法吗?
可能不会,因为 calldata 用于在进行外部交易时提供的数据。与存储相比,用途截然不同。
呼叫数据是只读的。您可以将 calldata 变量解码到内存中,但反之则不行。
不幸的是,数组切片仅针对 calldata 实现。对于内存和存储,它有点复杂,还没有实现(见问题#7423)。
你的解决方法是一个一个地复制字符,这实际上是编译器在幕后所做的,因为你试图 return 来自 [=17= 的切片] 函数(将切片具体化为数组)。