Hello Library!
Compartmentalize
In addition to building applications in Rust you can also build libraries, code that can be used by other Rust applications.
If we were starting from 0, we could use the command cargo new --lib hello_world
to create a new library but for simplicity lets just add a library to this project. We can do that by adding a lib.rs
file to the src
folder.
In that file we are going to write our first two rust functions, they'll look like this.
lib.rs
pub fn generate_greeting() -> String {
generate_custom_greeting("world")
}
pub fn generate_custom_greeting(name: &str) -> String {
format!("Hello, {}!", name)
}
Rust's syntax can seem strange if you are coming from a dynamically typed languages, so what does all of that mean up there.
We use the keyword pub
to make sure that this function will be available from outside of our library and then the keyword fn
which is short for function. Next we give our function a name and then define any parameters, that part shouldn't be all that strange. Our arguments are going to be defined with a name then a colon and then the type, if you have more than one parameter you can just separate them with a comma like you would expect. The last thing to add to complete a function signature is the return type, to do this we use the thin arrow (->
) followed by the type the function returns, if you aren't returning anything you can omit this part (no need to return void
or anything like that). One of the strangest looking things about rust functions is that return values are the last line of a function's body with no semi-colon. So looking over the above code, we have two functions: generate_custom_greeting
will take in a string and then replace the curly braces in "Hello, {}!" with the argument and returns the result, while generate_greeting
will use generate_custom_greeting
to create the string "Hello, world!" and return that.
Now if we were to run cargo build --lib
we would generate a library file that could be used from other rust
programs, but how would we use that?