Strings & String Builders
🔤 Strings, C-Strings & String Builders in Odin
In Odin, string is a fat pointer (pointer + byte length), completely independent from null-terminated C-strings (cstring).
🧱 1. string vs cstring
1. Odin string:
[ rawptr data ] [ int len ] (Can contain null bytes, length is O(1))
2. C-string (cstring):
[ rawptr data ] -> "Hello\0" (Length is O(N), terminates on first 0x00)
Conversions & Interop
- Odin
stringcstring: Usestrings.clone_to_cstring(s, allocator)or ensure a null terminator exists. cstringOdin string: Usestring(my_cstring)(reads up to the null byte).
âš¡ 2. High-Performance strings.Builder
Concatenating strings with + in loops causes massive heap fragmentation. Use strings.Builder backed by context.temp_allocator:
package main
import "core:fmt"
import "core:strings"
build_entity_report :: proc(id: int, hp: int) -> string {
b := strings.builder_make(context.temp_allocator)
strings.write_string(&b, "Entity ID: ")
strings.write_int(&b, id)
strings.write_string(&b, " | HP: ")
strings.write_int(&b, hp)
return strings.to_string(b)
}
🔗 Related Notes
- Dynamic Arrays & Slices — Slice memory layouts.
- Memory Management & Allocators — Custom arena allocators.
- Functions — C ABI procedures and interop.
- Odin Programming Language Index — Language overview.