flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

Generated rust code for table key of struct type does not compile

Open emesare opened this issue 6 months ago • 1 comments

Trying to use a struct type as the key for a table generates Rust code that does not compile, because the key lookup code uses cmp which requires the type to impl Ord.

Flatbuffer file:

struct MyKey {
    value:[ubyte:16];
}

table MyKeyValue {
    key:MyKey (key, required);
    value:string;
}

table MyData {
    kvs:[MyKeyValue];
}

root_type MyData;

Relevant error:

error[E0599]: the method `cmp` exists for reference `&MyKey`, but its trait bounds were not satisfied
   --> src/bug_generated.rs:139:9
    |
15  | pub struct MyKey(pub [u8; 16]);
    | ---------------- doesn't satisfy `MyKey: Iterator` or `MyKey: Ord`
...
139 |     key.cmp(&val)
    |         ^^^ method cannot be called on `&MyKey` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `MyKey: Ord`
            which is required by `&MyKey: Ord`

I understand why Ord is not derived for the struct as the byte representation is not eligible for derivation. However I believe you can sidestep it with a custom impl that would mimic the auto derive but reference the structure fields through the accessors functions, similar to what is currently being done for the impl Debug.

Repro repo: https://github.com/emesare/flatbuffers-bug-0

emesare avatar May 27 '25 15:05 emesare

This seems to be somewhat workable solution: https://github.com/emesare/flatbuffers/commit/e6c9c9068e53e8bd9ebe955eb105ca22985c1dad

emesare avatar May 27 '25 17:05 emesare

This issue is stale because it has been open 6 months with no activity. Please comment or label not-stale, or this will be closed in 14 days.

github-actions[bot] avatar Nov 25 '25 20:11 github-actions[bot]