Quiz — First homework: 0x check
Question
Your first Rust program. Check whether a given string is an Ethereum address starting with 0x. Combines &str.starts_with + .len() + if/else + && — the basics in one function.
Principle (minimum model)
- Function signature.
fn is_valid_address(addr: &str) -> bool. Borrow&str; returnbool. addr.starts_with("0x"). The standard&strmethod.has_prefixdoes not exist;containsis substring, not prefix.- Length check.
addr.len() == 42. Ethereum address = 40 hex digits +0xprefix = 42 chars total. - Idiomatic.
addr.starts_with("0x") && addr.len() == 42 && addr[2..].chars().all(|c| c.is_ascii_hexdigit())— three conditions ANDed. - In Alloy.
addr.parse::<Address>()delegates all of this to Alloy. Production code does this. - Rust Playground. https://play.rust-lang.org/ — try Rust without Alloy. URL-share for snippets.
Worked example + steps
First homework: 0x check
The simplest possible task:
Given a string that's supposed to be an Ethereum address, check whether it starts with
0xand print a message. As a stretch: also verify the length (42 characters total).
What you'll need
This is your first Rust program in the EVM stack tradition. Three primitives appear in every Rust program you'll ever write:
- Variables —
letandlet mut(we just covered these) - Methods — Rust strings have built-in methods. There's one that checks whether a string begins with another string. Find it in the std docs:
&strdocumentation - Conditionals —
if/else
You also need to know the length of an Ethereum address. Look it up if unsure (hint: 40 hex chars + the 0x prefix).
Try it yourself
Open Rust Playground and write a function with this signature:
fn is_valid_address(addr: &str) -> bool {
// your code
}
Test it against:
fn main() {
println!("{}", is_valid_address("0x1234567890abcdef1234567890abcdef12345678")); // true
println!("{}", is_valid_address("1234567890abcdef1234567890abcdef12345678")); // false
}
A few hints if you get stuck:
addr.-something — there's a method on&strwhose name is exactly what you wantaddr.len()returns the character byte length- Two boolean conditions are joined with
&&
Don't peek at the answer until you've tried writing it. The whole point of Rust is the compiler teaches you — let it.
Quiz
Once you've written and run your version, take the quiz below. Each question targets a specific Rust idiom — you should be able to answer them all from the experience of having written this function.
Summary (3 lines)
- Function
is_valid_address(addr: &str) -> bool=starts_with("0x") && len == 42 && all hex digits. Three conditions AND. - Alloy production:
addr.parse::<Address>()delegates everything. Rust Playground for Alloy-free experimentation. - Five quiz questions cover this homework and the basic syntax. Next: final Beginner quiz.