Unsafe pointers in Mojo
alloc hands back raw memory that you index directly and must free yourself.
from std.memory import alloc, memset_zero
def main():
var block = alloc[Int32](4)
memset_zero(block, 4)
print(block[0], block[3])
for i in range(4):
block[i] = Int32(i * i)
print(block.load(2))
block.store(3, Int32(100))
print(block[3])
block.free()
How it works
alloc[Int32](4)reserves four slots and returns anUnsafePointer.memset_zeroclears them; indexing,load, andstoreread and write.block.free()releases the block - nothing else will.
Keywords and builtins used here
Int32defformainprintrangevar
The run, in numbers
- Lines
- 13
- Characters to type
- 251
- Tokens
- 82
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 76 seconds.
Step 1 of 4 in Memory, step 17 of 22 in Parameters & SIMD.