Instantiating a type generated from a schema follows a three-step hierarchy. You do not interact with the raw buffer directly; instead, you wrap it in layers of abstraction:
capnp.Arena: A low-level wrapper around a []byte buffer. Use capnp.SingleSegment(nil) for a standard new arena.*capnp.Message: Allocates Cap'n Proto structs within an arena. Use capnp.NewMessage(arena) to create a new message and obtain its root segment.- Schema-generated type: A high-level wrapper around the
Message that provides getter and setter methods. Use the NewRootXXX function (e.g., books.NewRootBook(seg)) to instantiate the top-level struct of a message.
Each field in your schema produces a getter (e.g., Title()) and a setter (e.g., SetTitle()).
// 1. Create Arena
arena := capnp.SingleSegment(nil)
// 2. Create Message
msg, seg, err := capnp.NewMessage(arena)
if err != nil {
panic(err)
}
// 3. Create Schema Type (Root)
book, err := books.NewRootBook(seg)
if err != nil {
panic(err)
}
// Use Getters/Setters
_ = book.SetTitle("War and Peace")
title, _ := book.Title()