在AssemblyScript中实例化数组的三种不同方法

时间:2019-09-17 02:00:07

标签: assemblyscript nearprotocol

我正在写一个智能合约,想使用数组来操纵数据,但是查看AssemblyScript文档,我不确定最好的处理方法。

我觉得只用:

let testData:string[] = []

但是当我查阅assemblyscript文档时,建议使用三种创建数组的方法:

// The Array constructor implicitly sets `.length = 10`, leading to an array of
// ten times `null` not matching the value type `string`. So, this will error:
var arr = new Array<string>(10);
// arr.length == 10 -> ERROR

// To account for this, the .create method has been introduced that initializes
// the backing capacity normally but leaves `.length = 0`. So, this will work:
var arr = Array.create<string>(10);
// arr.length == 0 -> OK

// When pushing to the latter array or subsequently inserting elements into it,
// .length will automatically grow just like one would expect, with the backing
// buffer already properly sized (no resize will occur). So, this is fine:
for (let i = 0; i < 10; ++i) arr[i] = "notnull";
// arr.length == 10 -> OK

我何时要在另一种实例上使用一种实例化?为什么我不总是只使用开始时介绍的版本?

2 个答案:

答案 0 :(得分:1)

数组文字方法没问题。它基本上等同于

let testData = new Array<string>();

但是,有时您知道数组的长度是多少,在这种情况下,使用Array.create预分配内存会更有效。

答案 1 :(得分:1)

更新

PR Array.create已弃用,不应再使用。

旧答案

let testData:string[] = []

在语义上与

相同
let testData = new Array<string>()

AssemblyScript不支持未明确声明为可空的参考元素的预分配稀疏数组(带有孔的数组),例如:

let data = new Array<string>(10);
data[9] = 1; // will be compile error

您可以使用:

let data = new Array<string | null>(10);
assert(data.length == 10); // ok
assert(data[0] === null); // ok

Array.create,但在这种情况下,您的长度将为零。 Array.create实际上只是为后备缓冲区保留容量。

let data = Array.create<string>(10);
assert(data.length == 0); // true

对于普通(非引用)类型,您可以使用常规方法,而无需担心nullabe或通过Array.create创建数组:

let data = new Array<i32>(10);
assert(data.length == 10); // ok
assert(data[0] == 0); // ok