push(x: T) - > unit- 모듈
- 컬렉션 →
- 수신자
- Array<T>
- 최소 인자 수
- 1
- 최대 인자 수
- 1
Declaration and parameters
사용 조건
기본 포함 · 예
These types are provided by the language. No module import is required.
The declarations below describe the standard operations on built-in values.
수신자
Array<T>
매개변수 제약
Array<T>.get(i: int) returns Option<T>. An index from zero to one less than the length returns Some with that element. A negative index or an index at or past the length returns None().
get never faults for its index. Use values[i] when an index outside the array is a program error. That expression faults under the access rule.
The length property returns the number of elements as int. An empty array has length 0.
Array<T>.push(x: T) returns unit. It appends x after the last element and increases the length by one. Earlier elements keep their positions.
Push writes to the array value. The receiver must be rooted in a let mut binding. Other array values are unchanged under collection value semantics.
결과
The declared result type is unit.
효과
실패
Result and effects
The length grows by one and earlier elements keep their positions. Other array values are unchanged.
Related entries
Read, count and append array elements
Read, count and append array elements
Array<T>.get(i: int) returns Option<T>. An index from zero to one less than the length returns Some with that element. A negative index or an index at or past the length returns None().
get never faults for its index. Use values[i] when an index outside the array is a program error. That expression faults under the access rule.
The length property returns the number of elements as int. An empty array has length 0.
Array<T>.push(x: T) returns unit. It appends x after the last element and increases the length by one. Earlier elements keep their positions.
Push writes to the array value. The receiver must be rooted in a let mut binding. Other array values are unchanged under collection value semantics.
이유
A lookup that may miss returns its absence as a value, so reads of neighbors at the edges of a sequence need no separate bounds test. Indexing keeps its fault for indexes that a correct program never produces. The two intents keep two spellings. push builds a sequence in order without rebuilding it.
Read elements without faulting at the edges
import std.iolet names = ["a", "b", "c"]for index in ([-1, 0, 2, 3]) {match (names.get(index)) {case Some(name) => io.writeLine("{index}: {name}")case None() => io.writeLine("{index}: none")}}let empty: Array<string> = []io.writeLine("{empty.length}: {empty.get(0) ?? "none"}")
-1: none
0: a
2: c
3: none
0: none
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
-1: none0: a2: c3: none0: none
Append elements to a mutable array
import std.iolet mut names: Array<string> = []io.writeLine("{names.length}")names.push("a")names.push("b")io.writeLine("{names.length}: {names.join(",")}")
0
2: a,b
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
02: a,b