rdkafka::message::ToBytes is not implemented for `&str`
05:00 23 Nov 2025

I am trying to write a Rust program which generates random FX data and sends it to a Kafka topic.

The code I have written so far is quite short. It does not currently compile.

use rdkafka;
use rand;
use rand::seq::IndexedRandom;

fn main() {
    let mut config = rdkafka::config::ClientConfig::new();
    config.set("bootstrap.servers", "server:9092");

    let producer = config.create::().unwrap();

    let fx_G10 = ["EURUSD", "GBPUSD", "USDJPY", "AUDCAD", "AUDUSD", "USDCAD", "EURJPY"];

    let mut rng = rand::rng();

    loop {
        let fx = fx_G10.choose(&mut rng).unwrap();

        let payload = "example";

        let mut message = rdkafka::producer::BaseRecord::to("example")
            .payload(payload)
            .key(fx);

        producer.send().unwrap();
    }
}

The full error message is

the trait bound `&str: rdkafka::message::ToBytes` is not satisfied
the trait `rdkafka::message::ToBytes` is implemented for `str`
required for `&str` to implement `rdkafka::message::ToBytes`
base_producer.rs(132, 13): required by a bound in `BaseRecord::<'a, K, P, D>::payload`

My question is not "how do I fix this". I can figure out a way to make this compile, that is not a difficult problem.

What I do not understand is why this code doesn't currently compile.

The elements of fx_G10 are &'static str. The size of each element of fx_G10 is known at compile time. The length of each element is the same, however obviously that need not necessarily be the case in general. One of these elements could have different length.

Therefore, all we can know about fx_G10 at compile time is that it contains references to str (&str) objects, but the sizes of these things might be different.

rdkafka::message::ToBytes is implemented for str, String and some other types. (See: https://docs.rs/rdkafka/latest/rdkafka/message/trait.ToBytes.html)

Strings are dynamically sized. In other words, their size is not known until runtime. Therefore, whatever rdkafka::message::ToBytes does internally, it must be able to cope with references to data which has a size which is dynamic (not known until runtime).

So why isn't it implemented for &str?

rust