Rust
Learn Rust by typing real, idiomatic code.
Type your way into Rust's hardest ideas: ownership and borrowing, lifetimes, traits, enums, and the Result/Option pattern matching that replaces exceptions. Each snippet is idiomatic, compiling Rust, and an AI tutor explains every line — why the borrow checker rejected a move, what a trait bound buys you — so the concepts stick as your fingers learn the syntax.
Progress0 / 838 solved · 0/50 sections
best wpm
0
avg wpm
0
accuracy
0%
runs
0
level
1
rating
1000
Run Rust on your machine
1. Install the toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh2. Save your code as hello.rs, then compile & run
rustc hello.rs && ./hello # or: cargo runprogress by section
1Fundamentals0/42start →
Hello, RustFloats, bool, charfor over a rangeInteger typesType limitsBindingswhile loopCasting with asfor with enumerateFunctionsloop with a valueOptionParse from textSearch within textSplit a stringTrim and change caseunwrap & expectwhile letBorrowing (&)CloneCopy vs moveEnums with dataif let & matches!Read a line from stdinLabeled loopsMatch a ResultMutable borrow (&mut)Option fallbacksOverflow handlingResultJoin and split linesDurationsMeasure elapsed timeRead and parse a numberWrite to stdout and stderrIteratorsThe ? operatorScope and dropSlicesSeconds since the epochA custom error typeOption and match
2Strings In Depth0/18start →
String to &str and backBuild a String by pushingCompare String and &strBuild without movingWays to make a StringString vs &strReturn an owned StringTake &str, accept bothSlice by byte indexConcatenate with +There is no s[0]Grow a caller's Stringsplit yields borrowsMind char boundariesReturn a borrowed &strAccept any string-like typeBorrow or own with CowA struct that borrows text
3Values & References0/18start →
Borrow to readClone to keep bothCopy types are duplicatedValue vs referenceDereference with *Borrow just one fieldPassing by value movesMutable borrowBorrow instead of moving big dataSlices are borrowsBox: an owned heap pointerMake a struct CopyPass a &mut onwardReturn a referenceOwn vs borrow: the API choiceShared xor mutableRc: shared ownershipA raw pointer
4Slices & Arrays0/18Unlock →
5Data structures0/64Unlock →
Array & slice: createArray & slice: iterateArray & slice: retrieveString: create & pushVec: createVec: insertVec: retrieveVecDeque: insertVecDeque: iterateVecDeque: retrieveVecDeque: removeHashMap: insertHashMap: retrieveHashSet: filterHashSet: insertHashSet: retrieveArray & slice: filterArray & slice: sortString: concatenateString: find / containsString: remove / truncateString: replaceString: retrieveVec basicsVec: filterVec: remove / eraseVec: sortVec: updateBox: heap allocationBTreeMap: insertBTreeMap: iterate sortedBTreeMap: retrieveBTreeMap: removeBTreeSet: insertBTreeSet: min & maxBTreeSet: removeHashMap word countHashMap: insert-or-updateHashMap: filterHashMap: remove / eraseHashMap: sort entriesHashMap: updateHashSet dedupHashSet: set operationsHashSet: remove / eraseBinaryHeap: remove (max first)BinaryHeap: insertBinaryHeap: sortLinkedList: filterLinkedList: insertLinkedList: retrieveLinkedList: removeString: sort charactersBTreeMap keeps orderBTreeMap: range queryBTreeSet: range / retrieveBinaryHeap: min-heapRc: shared ownershipVecDeque as a queueBox<dyn Trait>: trait objectsEnums and matchA generic stackRc<RefCell>: shared mutabilityA binary tree with Box
6Iterators0/20Unlock →
7Traits0/20Unlock →
8Generics0/20Unlock →
Trait boundGeneric enumGeneric functionGeneric structTwo type parametersBounded impl blockDefault boundimpl Trait argumentimpl Trait returnGeneric over iterablesGeneric methodsGeneric minMultiple boundsNewtype wrapperwhere clausesConst genericsGeneric with a closure paramStatic vs dynamic dispatchBlanket implPhantomData
9Lifetimes0/20Unlock →
Lifetime elisionClosures borrowFunction pointers are 'staticA lifetime parameterReturning a field reference'static lifetimeReferences in an enumimpl on a borrowing structA reference wrapperA borrow can't outlive its ownerReturning a slice elementStruct holding a referenceTwo borrowed fieldsLifetime with a genericLongest in a slice of StringsA borrowed mutable fieldA borrowing parserTwo lifetimesLifetime bound on a genericReturning a borrowing iterator
10Closures0/20Unlock →
A closureCapturing the environmentExplicit types & bodyMultiple parametersCallbacksCapturing in a filterClosure as an argument (Fn)Function pointersClosures drive iteratorsmove closuressort_by with a closureA stateful FnMutCurryingFnMutFnOnceBorrow vs move captureReturning a closureBox<dyn Fn>Return different closuresHigher-order: compose
11Pattern Matching0/20Unlock →
Literals and _if let / elsematch as an expressionMatch an OptionOr-patternsRange patternsMatch a ResultDestructure structsDestructure tuplesTuple structswhile letBinding with @Struct-variant enumsMatch guardsMatch by referenceIgnore the middle with ..let elseSlice patternsMatch a Vec's shapeNested patterns
12Error Handling0/20Unlock →
expect for invariantsunwrap_or_defaultKeep only successes? in mainmap_errok_or? on OptionResult combinatorsunwrap_or_elseand_thenBox<dyn Error>Collect into a ResultAdd context to an errorImplement the Error traitMultiple error variantsChaining ?Mixed errors via Box<dyn Error>? auto-converts via FromtransposeError source (chaining)
13Option & Result0/20Unlock →
14Conversions0/15Unlock →
15Collection Conversions0/19Unlock →
Flatten nested VecsMap keys to VecMap values to VecPairs to a mapHashSet to sorted VecVec to BTreeSetVec to VecDequeVec to HashSetBoxing and unboxingVec to frequency mapMap keys to a HashSetHashMap to BTreeMapMap to Vec of pairsTwo Vecs to a mapVec and boxed sliceUnique, keeping orderGroup a Vec into a mapInvert a mapA Vec of trait objects
16Math0/46Unlock →
Math constantsFloat functionsInteger arithmeticmin, max, clampRoundingAverage of a sliceDegrees and radiansFactorialFractional partLogarithms & expNext power of twoabs_diff & signumTrigonometryAngle of a pointBit mathCopy a signEuclidean divisionDot productComparing floatsEuclidean div & modHyperbolic functionshypot & atan2Integer logarithmInverse trigonometryInteger square rootLinear interpolationLogarithm in any baseNaN and infinity checksVector magnitudeReciprocal and fused multiply-addBit rotationRound to N decimalsMin, max and range of a sliceReverse bytes and bitsMin/max of floatsGCD and LCMPrimality testMedianModeOverflowing arithmeticRemap a rangeSort floats with total_cmpVariance and standard deviationCombinations (nCr)Sieve of EratosthenesConvert to any base
17Encoding0/22Unlock →
String to bytesASCII checks and caseBytes to StringChar to code pointChar digit valueBinary, octal, hex formattingBig-endian bytesList code pointsEscape a charHex encodeLittle-endian bytesBytes vs charsParse a number in a baseLossy UTF-8 decodeCaesar cipherHex decodePercent-encodeROT13XOR cipherPercent-decodeBase64 decodeBase64 encode
18Random0/20Unlock →
Seed from the clockCoin flipPick a random elementRandom alphanumeric stringWeighted true/falseRandom bytesRandom enum variantA linear congruential generatorPassword generatorRandom seed from RandomStateRandom number in a rangeReproducible sequencesAn xorshift generatorRoll many diceSample k without replacementFisher-Yates shuffleRandom f64 in [0, 1)UUID-v4-shaped stringWeighted choiceNormal distribution
19Data I/O0/18Unlock →
Parse CSV into rowsTab-separated valuesBuild a CSV stringSelect one columnCSV into a number matrixSplit off the headerWhitespace-separated matrixRead a data fileSerialize records to CSVSkip blanks and commentsPrint an aligned tableWrite CSV to a fileWrite a matrix as textAppend a rowStream lines with BufReaderParse key=value configRound-trip write then readDrop unparseable rows
20Linear Algebra0/21Unlock →
Matrix shapeScalar multiplyA matrix of zerosElementwise addArgmax of a vectorIdentity matrixOne-hot encodeTraceStack rows (vstack)ReLU and sigmoidApply a function elementwiseColumn meansColumn sumsCosine similarityFlat storage, 2D indexingMatrix times vectorTransposeMatrix multiplyMin-max normalize columnsSoftmaxStandardize columns (z-score)
21Text Processing0/16Unlock →
22Date & Time0/24Unlock →
Leap yearDays in a monthDuration arithmeticDuration unitsElapsed since a SystemTimeSeconds to HH:MM:SSTime a block of workParse an ISO dateScale a DurationUNIX timestamp nowApply a fixed timezone offsetAverage durationBreak a Duration into partsDeadline checkDays between two datesParse a clock stringParse a timezone offsetThroughputAdd days to a dateDay of the weekEpoch days to dateDate to epoch daysFormat unix as ISO 8601Parse a datetime to unix
23Memory0/12Unlock →
24Modules0/20Unlock →
A moduleuseConstants in a moduleAn enum in a moduleGlob importNested modulesGrouped usePublic vs privateuse as (alias)crate:: pathself:: pathA small utility moduleA struct in a modulesuper::Flatten a deep pathPrivate fields, public getterpub(crate)Re-export with pub useReach a sibling moduleA trait in a module
25Macros0/20Unlock →
26Testing0/20Unlock →
assert! with a messageassert_ne!A unit testTesting a truth tableMultiple testsTesting string outputDoc comments + a testTesting an error caseA test helper#[ignore]Testing an OptionTesting a panic path#[should_panic]Testing a methodAsserting on a VecComparing floats in testsTest private functionsTests returning Resultshould_panic(expected)Table-driven tests
27Algorithms0/10Unlock →
28Sorting Algorithms0/12Unlock →
29Expression Parsing0/6Unlock →
30Idioms0/9Unlock →
31OOP & Traits0/8Unlock →
32Trait Objects0/14Unlock →
33Design Patterns0/14Unlock →
35File I/O0/6Unlock →
36Filesystem0/18Unlock →
Does a path exist?Copy a fileCreate nested directoriesFiles vs directoriesBuild a pathList a directoryRename or moveChange the extensionFile metadataPath componentsRemove files and treesSorted listingWrite to the temp dirAbsolute pathFilter by extensionLast modified timeTotal size of a treeWalk the tree
37Networking0/16Unlock →
38Concurrency0/25Unlock →
Share read-only data with ArcIterate a receiverCollect results from threadsMultiple producersPush into a shared VecRun setup onceSpawn a threadtry_locktry_recvAn atomic stop flagBarrierRelease the lock earlyMove into a threadConcurrent readers, one writerParallel sum with scoped threadsBounded channelFan out, collect resultsCompare-and-swapMessage passing with a channelCondvar wait/notifyShared state with Arc<Mutex>Recover a poisoned MutexScoped threadsAtomicsRwLock
39Unsafe & FFI0/14Unlock →
40Commands0/14Unlock →
41Array0/10Unlock →
43String0/10Unlock →
45Interval0/5Unlock →
46Linked List0/6Unlock →
47Tree0/14Unlock →
Maximum Depth of Binary TreeInvert Binary TreeSame TreeLowest Common Ancestor of a BSTBinary Tree Level Order TraversalSubtree of Another TreeImplement Trie (Prefix Tree)Kth Smallest Element in a BSTValidate Binary Search TreeAdd and Search WordConstruct Binary Tree from Preorder and InorderBinary Tree Maximum Path SumSerialize and Deserialize Binary TreeWord Search II