jsrosetta

Collections

Uint8Array

Node.js's Uint8Array (set, subarray, fill) compared to Go's []uint8, Rust's &[u8], Swift's [UInt8], and Java's byte[].

Minimum versions
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.58Swift ≥ 4.0Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

Node.js's Uint8Array is a TypedArray holding only unsigned 8-bit integers, with built-in set/subarray/fill methods. Go has no dedicated type for this — you use []uint8 directly (identical to []byte, since byte is just an alias for uint8), along with the language's ordinary slice and loop operations. Rust is similar: Vec<u8>/&[u8] plus the slice's built-in methods (copy_from_slice, fill). Swift uses [UInt8] (a value type). Java is the odd one out: byte is always signed (-128..127), there's no unsigned 8-bit type, and a raw array (byte[]) has no lightweight "view" like subarray/slice — Arrays.copyOfRange always makes a copy.

Initializing, writing, and taking a subarray

const array = new Uint8Array(10)
console.log(array) // Uint8Array(10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
const offset = 1
array.set([1, 2, 3], offset)
console.log(array) // Uint8Array(10) [0, 1, 2, 3, 0, 0, 0, 0, 0, 0]
 
const sub = array.subarray(2)
console.log(sub) // Uint8Array(8) [2, 3, 0, 0, 0, 0, 0, 0]
 
const sub2 = array.subarray(2, 4)
console.log(sub2) // Uint8Array(2) [2, 3]

Fill and length (byteLength)

const value = 9
const start = 5
const end = 10
array.fill(value, start, end)
console.log(array) // Uint8Array(10) [0, 1, 2, 3, 0, 9, 9, 9, 9, 9]
 
console.log(array.byteLength) // 10

Reference: github.com/miguelmota/golang-for-nodejs-developers#uint8-arrays