Help serializing a protobuf message to a file

Hi everyone,

I am playing with protobuf for Rust and I got everything compiled and running, but can't figure out how to write to a file.

I have a very simple .proto file:

message Foo {
  required string greeting = 1;

and associated code in

extern crate protobuf;
mod foo;
use foo::Foo;
use protobuf::Message;
use protobuf::CodedOutputStream;

use std::io::prelude::*;
use std::fs::File;

fn main() {
    let mut file = File::create("foo.txt").unwrap();
    let mut f = Foo::new();

    f.set_greeting("Hi there!".to_string());

    let mut cos = CodedOutputStream::new(&mut file);

    f.write_to(&mut cos);

    println!("{:?}", f);

It compiles and runs, but the created foo.txt has zero bytes. Any help?

May I suggest including some examples in protobuf? I think it would be really helpful to get it up and running.

Thank you very much.


Have you tried calling flush on the stream?

Well, the file is mutably borrowed at

    let mut cos = CodedOutputStream::new(&mut file);

so I can't call flush() later on. Anyway, I would expect that the file self-flushes on close.

Changed the topic to better fit the thread.

Oh, I realize now: on the stream. That worked indeed, thanks! But I would have expected for the stream to self-flush on exiting the code.

Yes, that would be more idiomatic behavior. (It's what std::io::BufWriter does, for example.) I think it's worth filing an issue on the protobuf crate to request this change.

1 Like

rust-protobuf author here.

CodedOutputStream does not flush on drop intentionally.

I think BufWriter works incorrectly. See the discussion here for the explanation.


I see, it's an interesting discussion, thanks for the pointer. I somehow feel now going back to the old pre-RAII days, having to remember to call my .flush in every possible returning path of my function, but I think that there is no clear-cut solution here.

Thanks for the library, by the way! Any hope of ever getting official google status?

Any hope of ever getting official google status?

I doubt so. Official implementations are the implementations developed inside Google. All other implementations are unofficial.