solidity中datalocation数据位置
1.memory:修饰的变量的数据存储在内存中;
2.storage:修饰的变量的数据将永久存储在区块链上。
3.calldata:一般只有在外部函数(external)的参数被强制指定为calldata,这种数据位置是只读的,不会持久化到区块链中。internal 接口中常常出现
interface IanimalEat{
function eat(string calldata myname) external returns(string memory);
}
参考: https://blog.youkuaiyun.com/yuanziwoxin/article/details/85249384
值类型赋值,总是创建独立副本。
storage也称为引用传递:
1.在storage和 memory之间(或来自 calldata)的赋值总是创建一个独立的副本。
2.从 memory到 memory的赋值仅创建引用。这意味着对一个内存变量的更改在引用相同数据的所有其他内存变量中同样有效。
3.从storage到本地storage变量的赋值也仅赋值一个引用。
函数中 uint[] y = x; 默认是storage
函数参数,uint[] memoryArray 默认是引用位置
pragma solidity ^0.4.0;
contract TestLoc {
uint[] x; // x的存储位置是storage
// memoryArray的存储位置是 memory
function f(uint[] memoryArray) public returns (uint[]) {
x = memoryArray; // 从 memory 复制到 storage
uint[] y = x; // storage 引用传递局部变量y(y 是一个 storage 引用)
y[1] = 2;

本文深入探讨了Solidity中的数据位置,包括memory、storage和calldata。memory用于临时存储变量,storage用于永久存储在区块链上,而calldata是外部函数参数的只读位置。在不同位置之间的赋值操作涉及到数据复制和引用传递,影响到 gas 消耗。例如,从storage到memory的赋值会复制数据,而storage到storage的赋值仅创建引用。理解这些概念对于编写高效且经济的智能合约至关重要。
最低0.47元/天 解锁文章
2139

被折叠的 条评论
为什么被折叠?



