https://cryptozombies.io/en/lesson/1/chapter/6

 

#1 Solidity Tutorial & Ethereum Blockchain Programming Course | CryptoZombies

CryptoZombies is The Most Popular, Interactive Solidity Tutorial That Will Help You Learn Blockchain Programming on Ethereum by Building Your Own Fun Game with Zombies — Master Blockchain Development with Web3, Infura, Metamask & Ethereum Smart Contracts

cryptozombies.io

3장: 상태 변수와 정수

컬렉션을 원할 때 배열 을 사용할 수 있습니다 . Solidity에는 고정 배열과 동적 배열의 두 가지 유형의 배열이 있습니다.

// Array with a fixed length of 2 elements:
uint[2] fixedArray;
// another fixed Array, can contain 5 strings:
string[5] stringArray;
// a dynamic Array - has no fixed size, can keep growing:
uint[] dynamicArray;

구조체 의 배열을 만들 수도 있습니다 . 이전 장의 Person구조체 사용:

Person[] people; // dynamic Array, we can keep adding to it

상태 변수가 블록체인에 영구적으로 저장된다는 것을 기억하십니까? 따라서 이와 같은 구조체의 동적 배열을 만드는 것은 일종의 데이터베이스 같은 계약에 구조화된 데이터를 저장하는 데 유용할 수 있습니다.

공개 배열

배열을 으로 선언할 수 있으며 public, Solidity는 자동으로 이에 대한 getter 메서드를 생성합니다. 구문은 다음과 같습니다.

Person[] public people;

그러면 다른 계약이 이 배열에서 읽을 수 있지만 쓸 수는 없습니다. 따라서 이것은 계약에 공개 데이터를 저장하는 데 유용한 패턴입니다.


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;

}

 

 

새 구조체 만들기

Person이전 예제의 구조체를 기억 하십니까?

struct Person {
  uint age;
  string name;
}

Person[] public people;

이제 새로운 Persons를 생성하고 people배열에 추가하는 방법을 배울 것입니다.

// create a New Person:
Person satoshi = Person(172, "Satoshi");

// Add that person to the Array:
people.push(satoshi);

이것들을 함께 결합하고 한 줄의 코드로 수행하여 깔끔하게 유지할 수도 있습니다.

people.push(Person(16, "Vitalik"));

배열의 끝에array.push() 무언가를 추가 하므로 요소는 추가한 순서대로 배열됩니다. 다음 예를 참조하십시오.

uint[] numbers;
numbers.push(5);
numbers.push(10);
numbers.push(15);
// numbers is now equal to [5, 10, 15]

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 {
        zombies.push(Zombie(_name, _dna));
    }

}

'스터디' 카테고리의 다른 글

solidity 2022/10/02 CryptoZombies - 3  (0) 2022.10.02
solidity 2022/10/02  (0) 2022.10.02
Smartcontract Openzeppelin 22.09.18  (0) 2022.09.18
solidity 2022.09.04  (0) 2022.09.04
Solidity 2022.09.03  (0) 2022.09.03
블로그 이미지

wtdsoul

,