Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plain Ol' Go Structs #33

Closed
zombiezen opened this issue Jun 8, 2016 · 0 comments
Closed

Plain Ol' Go Structs #33

zombiezen opened this issue Jun 8, 2016 · 0 comments

Comments

@zombiezen
Copy link
Contributor

Similar to the support planned for C++: https://groups.google.com/d/topic/capnproto/Reg0wInHBdY/discussion

Design sketch:

package pogs // import "zombiezen.com/go/capnproto2/pogs"

// GeneratedStruct is the interface implemented by a struct generated by capnpc-go.
type GeneratedStruct interface {
  GeneratedStruct() (id uint64, schemaData []byte, s capnp.Struct)
}

// Unmarshal copies from a Cap'n Proto struct to a plain Go struct.
func Unmarshal(val interface{}, s GeneratedStruct) error {
  // ...
}

// Marshal copies from a plain Go struct into a Cap'n Proto struct.
func Marshal(s GeneratedStruct, val interface{}) error {
  // ...
}

Usage:

// Assuming you have a capnp schema foo.capnp:
// struct Foo {
//   bar @0 :UInt64;
// }

type Foo struct {
    Bar uint64
}

func main() {
    msg, err := capnp.Unmarshal(myByteSource)
    if err != nil {
        panic(err)
    }
    foo, err := fooschema.ReadRootFoo(msg)
    if err != nil {
        panic(err)
    }
    // New API:
    var fooStruct Foo
    if err := pogs.Unmarshal(&fooStruct, foo); err != nil {
        panic(err)
    }
    fmt.Println(fooStruct.Bar)

    // And new API for writing back out:
    if err := pogs.Marshal(foo, &fooStruct); err != nil {
        panic(err)
    }
        fmt.Print(msg.Marshal())
}

capnpc-go could be optionally extended to generate the structs automatically, but much like the json package, users could also define narrow Go structs if they only need certain fields.

cc @lvdlvd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant