Your First Rust Programme
Write a small text-mocking programme directly on the BeagleBone Black Revision D. Start with a single source file, compile it using rustc, and progressively introduce functions, structs, methods and traits.
Practical Checklist
1. Create and compile a Rust programme
-
Connect to your BeagleBone Black using the SSH procedure from Getting Started. Confirm the compiler is available.
rustc --version uname -mThe architecture should report
armv7l. Unlike a hosted browser playground,rustchere produces a native executable for the board. -
Create a new directory and open a source file.
- rust/
- first_program/
- main.rs
- first_program/
mkdir -p ~/rust/first_program cd ~/rust/first_program nano main.rsA
.rsfile contains Rust source code. Save and exitnanoafter entering the code below. - rust/
-
Write the smallest useful programme.
fn main() { println!("Hello from the BeagleBone Black!"); }fndeclares a function,mainis the entry point, andprintln!is a macro (note the!). -
Compile and execute it.
rustc main.rs ./mainExpected output:
Hello from the BeagleBone Black!rustc main.rscreates an executable namedmainby default../mainruns it from the current directory.
2. Variables and text
-
Replace the contents of
main.rswith:fn main() { let message = "Hello"; println!("Original: {}", message); }letintroduces a binding.messageis immutable by default; the string literal has type&str. -
Compile and run again, this time choosing an executable name:
rustc main.rs -o text_mocker ./text_mockerOriginal: Hello -
Run the code here and read about the difference between
&strandString:fn main() { let borrowed: &str = "Hello"; let mut owned = String::from("Goodbye"); owned.push_str(", Rust!"); println!("{}", borrowed); println!("{}", owned); }
3. Functions and return values
-
Replace
main.rswith the following code. It makes alternating characters lowercase and uppercase, starting with lowercase.fn mock_text(input: &str) -> String { let mut result = String::new(); for (index, character) in input.chars().enumerate() { if index % 2 == 0 { result.push(character.to_ascii_lowercase()); } else { result.push(character.to_ascii_uppercase()); } } result } fn main() { println!("{}", mock_text("Hello")); }Observe that
-> Stringdeclares a return type and the finalresultexpression has no trailing semicolon.mutpermits modification of the localresultvariable. -
Compile and run it.
rustc main.rs -o text_mocker ./text_mockerhElLo
4. Structs and inherent implementations
-
Replace the programme with a
TextMockerstruct and an inherent implementation (impl TextMocker).struct TextMocker { text: String, } impl TextMocker { fn new(text: &str) -> Self { Self { text: String::from(text) } } fn render(&self) -> String { let mut result = String::new(); for (index, character) in self.text.chars().enumerate() { if index % 2 == 0 { result.push(character.to_ascii_lowercase()); } else { result.push(character.to_ascii_uppercase()); } } result } } fn main() { let message = TextMocker::new("Hello"); println!("{}", message.render()); }Selfrepresents the type being implemented.&selfborrows the struct for reading without moving or changing its storedString. -
Build and run using the same compiler command.
rustc main.rs -o text_mocker ./text_mockerhElLo
5. Traits and trait implementations
A trait describes behaviour that types may implement. It does not contain the text itself; the struct stores data, while the trait specifies an operation.
-
Replace
main.rswith the complete version below. Compare the two different forms ofimpl.struct TextMocker { text: String, } impl TextMocker { fn new(text: &str) -> Self { Self { text: String::from(text) } } } trait Transform { fn transform(&self) -> String; } impl Transform for TextMocker { fn transform(&self) -> String { let mut result = String::new(); for (index, character) in self.text.chars().enumerate() { if index % 2 == 0 { result.push(character.to_ascii_lowercase()); } else { result.push(character.to_ascii_uppercase()); } } result } } fn main() { let message = TextMocker::new("Hello"); println!("{}", message.transform()); } -
Compile and run.
rustc main.rs -o text_mocker ./text_mockerhElLo
6. Read and use compiler errors
-
In the last
main()function, temporarily changemessage.transform()tomessage.unknown_method()and compile again.rustc main.rs -o text_mockerInspect the diagnostic. Which type is involved? Which method could the compiler not find?
-
Restore
message.transform()and compile successfully before continuing to the next chapter.
7. Independent exercise
Implement Transform for Shout and use self.text.to_ascii_uppercase(). The implementation of the trait method must have the same signature: fn transform(&self) -> String.
The following is an addition to the working programme; insert it before main() and update main() as shown.
struct Shout {
text: String,
}
impl Transform for Shout {
fn transform(&self) -> String {
self.text.to_ascii_uppercase()
}
}
fn main() {
let mocker = TextMocker::new("Hello");
let shout = Shout { text: String::from("Hello") };
println!("{}", mocker.transform());
println!("{}", shout.transform());
}
Expected output: hElLo and HELLO on separate lines.