美文网首页
solidity中stroage与memory 的区别

solidity中stroage与memory 的区别

作者: P叔 | 来源:发表于2018-05-16 17:44 被阅读0次

在区块链里,区块链本身就是一个数据库。如果你使用区块链标记物产的所有权, 归属信息将会被记录到区块链上,所有人都无法篡改,以标明不可争议的拥有权。

在solidity编程中,有一个数据位置的属性用来标识变量是否需要持久化到区块链中。

我们可以通过 —— storage 或 memory 这两个关键字来存储变量

storage 与 memory 修饰的变量的区别

默认情况下,全局点状态变量会保存到区块链上,局部到变量保存在内存当中 storage修饰的变量是指永久存储在区块链中的变量。 

Memory修饰变量则是临时的,当外部函数对某合约调用完成时,内存型变量即被移除。 你可以把它想象成存储在你电脑的硬盘或是RAM中数据的关系。 但是在很多时候你都用不到这些关键字,默认情况下 Solidity 会自动处理它们。 

但是很多时候也需要我们进行一些特殊处理,下面我们通过代码来看一下.

contract Person {

  struct Person {

    string name;

    string sex;

  }

  Person[] persons;

  function eatSandwich(uint _index) public {

    // Person person = persons[_index];

    // ^ 看上去很直接,不过 Solidity 将会给出警告

    // 告诉你应该明确在这里定义 `storage` 或者 `memory`。

    // 所以你应该明确定义 `storage`:

    Person storage myPerson = persons[_index];

    // ...这样 `mySandwich` 是指向 `sandwiches[_index]`的指针

    // 在存储里,另外...

    myPerson.sex = "女!";

    // ...这将永久把 `sandwiches[_index]` 变为区块链上的存储

    // 如果你只想要一个副本,可以使用`memory`:

    Person memory anotherPerson = persons[_index + 1];

    // ...这样 `anotherSandwich` 就仅仅是一个内存里的副本了

    // 另外

    anotherPerson.sex = "Eaten!";

    // ...将仅仅修改临时变量,对 `sandwiches[_index + 1]` 没有任何影响

    // 不过你可以这样做:

    persons[_index + 1] = anotherPerson;

    // ...如果你想把副本的改动保存回区块链存储

  }

}

通过以上代码,我们就可以在某些场合下也需要你显式地声明 storage 或 memory了!

相关文章

网友评论

      本文标题:solidity中stroage与memory 的区别

      本文链接:https://www.haomeiwen.com/subject/nfkmdftx.html