-2

If I create a new cargo "package" with cargo new --lib testlib I can see that the resulting directory structure contains a src/lib.rs file.

I am aware that cargo uses the name lib.rs as a special name with special meaning. In other words, if it sees something called lib.rs it knows that it should compile the containing source code into a single binary library. This binary library is then available to be linked with other binary executables.

Is it possible to change the name lib.rs to something else, perhaps by configuring Cargo via the Cargo.toml file, or otherwise?

Essentially, I would really rather call the library root something like kafkalib.rs. I am not sure if this is possible.

One alternative workaround which occurred to me would be to declare a module within lib.rs.

mod kafkalib;

And then either create ./kafkalib/mod.rs or kafkalib.rs, and put the associated Kafka library code in this file.

Then, helper code which is not directly related could either be placed in lib.rs directly, or in some other module adjacent to kafkalib.

Perhaps this "workaround" is actually the intended use? Since this is all still new to me I can't be sure what the most sensible approach is. The above is really a guess.

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • 2
    https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target – Stargateur May 12 '23 at 10:59
  • 2
    It seems completely unnecessary though, what does `kafkalib/src/kafkalib.rs` as crate root give you that `kafkalib/src/lib.rs` does not, for removing a consistent entry point? – Masklinn May 12 '23 at 12:14

1 Answers1

2

OOH, I get it I do: I write Typescript for a living and it's extremely annoying (especially when using find or it's fuzzy descendants) to have every other file be named index.ts.

OTOH, conventions exist usually for good reason and I would stick with lib/mod/main.rs where appropriate. If I (or anyone else, including you 6 months from now) have to troubleshoot a problem with your crate it's just easier to tell at a glance where the entry point is without having to open up Cargo.toml. Just sayin.

But if you can't resist, as Stargateur links in the comments you can set the [lib] section of Cargo.toml just like with [[bin]] to configure the target.

[lib]
name = "whatever"
path = "src/kafkalib.rs" 
Jared Smith
  • 19,721
  • 5
  • 45
  • 83