繁体   English   中英

“内存”和“存储”关键字有什么区别

[英]What is the difference between "memory" and "storage" keyword

pragma solidity >=0.5.0 <0.6.0;

contract ZombieFactory {

    uint dnaDigits = 16;
    uint dnaModulus = 10 ** dnaDigits;

    struct Zombie {
        string name;
        uint dna;
    }

    Zombie[] public zombies;

    function createZombie (string memory _name, uint _dna) public {
        // start here
    }

}

在这里我很困惑,因为根据这篇文章https://ethereum.stackexchange.com/questions/1701/what-does-the-keyword-memory-do-exactly?newreg=743a8ddb20c449df924652051c14ef26

“结构的局部变量默认在存储中,但函数参数始终在内存中” 那么这是否意味着在这段代码中,当我们将字符串 _name 作为函数参数传递时,它会被分配到内存中,还是会像所有其他状态变量一样保留在存储中?

存储在区块链中存储数据并且它保持不变。 内存存储临时变量,包括在函数中(在本例中为 _name),并且在执行此函数时它们的生命周期受到限制。 因此,当我们将字符串 _name 作为函数参数传递时,它将被分配给内存,而 struct(name) 中的变量将被分配给存储。

所有状态变量都永久存储在storage中。 它就像硬盘存储。

内存就像 RAM。 当合约完成其代码执行时,内存被清除。

有时在声明状态变量后,您想在函数中对其进行修改。 例如你定义

 Zombie[] public zombies;

function createZombie (string memory _name, uint _dna) public {
        Zombie storage firstZombie=zombies[0]
        // mutate the name of the firstZombie
        firstZombie.name=_name
        // you have actually mutated state variable zonbies
    }

如果您使用memory关键字,您实际上会将值复制到内存中:

function createZombie (string memory _name, uint _dna) public {
            // firstZombie is copied to the memory
            // New memory is allocated.
            Zombie memory firstZombie=zombies[0]
            // mutate the name of the firstZombie
            firstZombie.name=_name
            return firstZombie
            // this did not mutate the state variable zombies
            // after returning allocated memory is cleared
        }

在solidity中,函数参数变量存储在内存中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM