<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Taufik Hidayat on Medium]]></title>
        <description><![CDATA[Stories by Taufik Hidayat on Medium]]></description>
        <link>https://medium.com/@yumtaufikhidayat?source=rss-b1b71b5dd036------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fVpG8n_PYfrCJspAuo-1ZQ.png</url>
            <title>Stories by Taufik Hidayat on Medium</title>
            <link>https://medium.com/@yumtaufikhidayat?source=rss-b1b71b5dd036------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:00:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yumtaufikhidayat/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Chat to Database: Building My Own MCP Server for Claude]]></title>
            <link>https://medium.com/codetodeploy/from-chat-to-database-building-my-own-mcp-server-for-claude-a4f7fc9f24c0?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f7fc9f24c0</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 07:33:02 GMT</pubDate>
            <atom:updated>2026-10-22T18:55:01.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjTF16H7dbLUDn3Mj8OqqA.png" /></figure><p>Every time I found a job listing that looked like a good fit, I’d open Notion, copy-paste the link and job description, fill in the fields by hand, and then forget to update the status once the application was underway. And so it went, looping. I did this for months and eventually realized the problem wasn’t the tracker itself, <a href="https://play.google.com/store/apps/details?id=id.yumtaufikhidayat.applymate"><strong>ApplyMate</strong></a>, the Android app I built and used by myself, but the gap in between: every listing I found through a chat with Claude had to be moved somewhere else, manually.</p><blockquote><em>💥 </em><strong><em>Master AI &amp; Tech Skills</em></strong><br>💰 One Plan. Multiple Courses. More Savings.<br>🔥 Get Up to 50% OFF | ⏰ Limited-Time Offer<br><a href="http://trk.udemy.com/OYJoKA"><em>👉 </em><strong><em>Enroll Now &amp; Start Learning</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITogvtC6mF2BUF35Qsd9pg.png" /></figure><p>After poking around with the <a href="https://developers.notion.com/guides/mcp/overview"><strong>Notion MCP</strong></a> for a while, I finally found the answer and it turned out to be simple. If Claude can already talk to Notion through a built-in MCP connector, why couldn’t it talk directly to my own app’s database? The same thing Notion does via MCP.</p><p>This is both the story and the full guide: what MCP is, why I chose Firestore and Railway, and how I built and deployed my own custom MCP server from scratch until it was usable from everyday chat.</p><blockquote>⚠️<strong> One thing I want to make clear upfront: this isn’t a bot that automatically applies to jobs. Every listing that lands in Firestore through this tool is one I’ve already decided, on my own judgment and criteria, to apply to. I’m still the one writing the intro, tailoring the CV, and sending the application by hand. What this tool does is exactly one thing: move that listing from chat into my tracker, ApplyMate, so it doesn’t get lost in the middle of a conversation.</strong></blockquote><h3>What Actually Happens When Claude Calls a Tool</h3><p>Model Context Protocol (MCP) is an open standard published by Anthropic, meant to connect AI assistants like Claude to tools and data outside the conversation. The difference from just answering in text: through MCP, Claude can actually take action: write a new row to a database, call a third party API, and read a file on your server.</p><p>The MCP server itself is just an ordinary program (in my case, Node.js/TypeScript) that registers one or more tools through a standardized schema. Claude reads that schema, knows when and how to call it, then sends a request to my server exactly like calling a REST API.</p><p>For my case, I only needed one tool: add_job_listing. Its one job: save the job listing being discussed in chat straight into Firestore.</p><h3>Who This Tutorial Is For</h3><p>If you’re an engineer who:</p><ul><li>Has your own app (indie app, side project, internal tool) with a database in the cloud</li><li>Uses Claude often for everyday work and is tired of manually copy-pasting between chat and the app</li><li>Is comfortable with Node.js basics and has touched Firebase before</li></ul><p>…this tutorial is written for you. I won’t be explaining Kotlin or Android basics here, the focus is purely on the server side, from Firebase to Railway.</p><h3>The Journey Map: From Chat to Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyGQmDLgf1lWfCvkZrJMJw.png" /><figcaption>Journey Map</figcaption></figure><pre>Claude chat -&gt; custom MCP server (Node.js/TypeScript) -&gt; Firestore -&gt; ApplyMate (Android)</pre><p>That one line of code above is the short version. The picture breaks it into four concrete stops: I ask Claude to save a listing in chat, my MCP server on Railway picks up that tool call and validates it, the data lands in Firestore as a new document in the job_listings collection tagged with my ownerId, and ApplyMate on Android is meant to pick it up on its next sync, though that last hop (the ApplyMate Lab variant that reads this data) is still in progress, more on that further down. What used to mean copy pasting company, position, link, and description into Notion by hand is now just Claude deciding on its own to call a tool, everything after that is plumbing I built once and never touch again (I wish 😀).</p><p>These are the four jumps I’ll walk through one by one:</p><ol><li>Setting up Firebase and Firestore as storage</li><li>Building the MCP server itself (three core files to start, more get added later when I extend it with update and delete)</li><li>Securing credentials before touching Git at all</li><li>Pushing it to GitHub, deploying to Railway, then connecting it to Claude as a custom connector</li></ol><h3>When and Why I Chose Firestore, Not Something Else</h3><p>I use Cloud Firestore (not Firebase Realtime Database, its older sibling product), because its document/collection structure maps more easily onto the Application data model that already exists in ApplyMate.</p><p>Steps to set it up in the Firebase Console:</p><ol><li>Open Firebase Console, use an existing project or create a new one.</li><li>Go to Firestore Database, click Create database.</li><li>If you want to separate an experimental environment from a production one already running (exactly my situation), Firestore has a named database feature, a second database besides (default) in the same project. This feature requires the Firebase Blaze (pay as you go) plan. I named mine labs.</li><li>Choose Native mode, and the nearest region (I used asia-southeast2, Jakarta).</li><li>Enable Anonymous Authentication in the Authentication tab. This lets my Android app sign in without a login form, and lets Firestore security rules restrict access per user.</li><li>Once the app has signed in anonymously at least once, check Authentication, then Users, to get the UID. This UID becomes the ownerId on every document the MCP server writes.</li></ol><p>A supporting reason, not the main one: the Firebase Admin SDK on the server and Firebase Anonymous Auth on the Android app both come with an authentication layer already built in. The server just calls cert(serviceAccount) to verify requests, and the app generates an ownerId per install, with no need to build a token system from scratch (signing, verifying, refresh, revoke) the way I would with Postgres or any other database that has no built-in auth provider. It&#39;s not the deciding factor, but it noticeably sped up development in this project&#39;s early solo phase.</p><h3>Getting the Admin Key</h3><p>The MCP server needs admin credentials to read and write Firestore from the server side, not from the client app.</p><ol><li>Project settings (gear icon), then the Service accounts tab</li><li>Click Generate new private key, confirm</li><li>A JSON file downloads automatically. Its filename usually follows the pattern &lt;project-id&gt;-firebase-adminsdk-&lt;hash&gt;.json</li></ol><blockquote><strong>⚠️ This is the point that’s easiest to underestimate, so I’ll say it plainly: DO NOT put this file inside the project folder that will be pushed to Git. This file is full admin credentials to your Firebase project. If it leaks, whoever has it can read, write, or delete the entire database. Store it in a separate folder outside the repo, for example ~/secrets/.</strong></blockquote><h3>How This Server Is Built: Three Files That Do Everything</h3><p>The stack I used:</p><ul><li>Node.js + TypeScript</li><li>@modelcontextprotocol/sdk, the official MCP SDK</li><li>firebase-admin, for Firestore access from the server</li><li>express, HTTP server</li><li>zod, tool input schema validation</li><li>cors, dotenv</li></ul><pre>npm init -y<br>npm install @modelcontextprotocol/sdk firebase-admin express zod cors dotenv<br>npm install -D typescript tsx @types/node @types/express @types/cors</pre><p>I deliberately kept the project structure small:</p><pre>src/<br>├── index.ts                 (Express HTTP server, auth middleware, MCP wiring)<br>├── firebase.ts              (Firebase Admin init, Firestore client)<br>└── tools/<br>    ├── addJobListing.ts     (add_job_listing tool: schema + handler)<br>    ├── updateJobListing.ts  (update_job_listing tool: schema + handler)<br>    ├── deleteJobListing.ts  (delete_job_listing tool: schema + handler)<br>    ├── jobListingLookup.ts  (shared findJobListing helper, used by update and delete)<br>    └── salaryEnums.ts       (shared SALARY_CURRENCIES and SALARY_PERIODS constants)</pre><h3>firebase.ts: The Point That Decides Whether This Server Can Live in the Cloud</h3><p>This is the part I thought through most carefully. PaaS platforms like Railway don’t have a persistent filesystem to permanently store a JSON credentials file. So I designed this code to accept credentials through two paths: a file path (for local development) or the JSON content directly as an environment variable (for production).</p><pre>import { cert, initializeApp, type App } from &quot;firebase-admin/app&quot;;<br>import { getFirestore, type Firestore } from &quot;firebase-admin/firestore&quot;;<br>import { readFileSync } from &quot;node:fs&quot;;<br><br>let app: App | undefined;<br>let db: Firestore | undefined;<br><br>export function getDb(): Firestore {<br>  if (db) return db;<br>  const credentialsJson = process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON;<br>  const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;<br>  const databaseId = process.env.FIRESTORE_DATABASE_ID;<br>  if (!credentialsJson &amp;&amp; !credentialsPath) {<br>    throw new Error(&quot;Set GOOGLE_APPLICATION_CREDENTIALS_JSON atau GOOGLE_APPLICATION_CREDENTIALS&quot;);<br>  }<br>  if (!databaseId) {<br>    throw new Error(&quot;FIRESTORE_DATABASE_ID belum di-set (named database, bukan default)&quot;);<br>  }<br>  const serviceAccount = credentialsJson<br>    ? JSON.parse(credentialsJson)<br>    : JSON.parse(readFileSync(credentialsPath as string, &quot;utf-8&quot;));<br>  app = initializeApp({ credential: cert(serviceAccount) });<br>  db = getFirestore(app, databaseId);<br>  return db;<br>}</pre><p>One small note that cost me a fair bit of time to notice: the second parameter of getFirestore(app, databaseId) is required if you&#39;re using a named database. Skip it, and Firestore silently falls back to (default) with no error at all.</p><h3>tools/addJobListing.ts: Where Claude Actually Understands What to Fill In</h3><p>The part that makes MCP feel like magic: the input schema uses zod, and Claude automatically understands which fields need filling just from their text descriptions, without me writing any extra prompt.</p><pre>import { z } from &quot;zod&quot;;<br>import { FieldValue } from &quot;firebase-admin/firestore&quot;;<br>import { getDb } from &quot;../firebase.js&quot;;<br><br>export const addJobListingInputShape = {<br>  company: z.string().min(1).describe(&quot;Nama perusahaan&quot;),<br>  position: z.string().min(1).describe(&quot;Posisi/jabatan yang dilamar&quot;),<br>  jobLink: z.string().url().describe(&quot;Link/URL lowongan pekerjaan&quot;),<br>  city: z.string().optional().describe(&quot;Kota kerja, kalau disebutkan&quot;),<br>  salary: z.string().optional().describe(&quot;Info gaji sebagai teks bebas&quot;),<br>  // ...other fields<br>};<br><br>export async function addJobListing(input) {<br>  const ownerId = process.env.APPLYMATE_OWNER_UID;<br>  const db = getDb();<br>  const doc = {<br>    ownerId,<br>    ...input,<br>    source: &quot;claude-mcp&quot;,<br>    createdAt: FieldValue.serverTimestamp(),<br>  };<br>  const ref = await db.collection(&quot;job_listings&quot;).add(doc);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: `Loker &quot;${input.position}&quot; di ${input.company} berhasil disimpan (id: ${ref.id}).` }],<br>  };<br>}</pre><h3>index.ts: The HTTP Server and Why I Didn’t Use OAuth</h3><p>This server uses static Bearer token authentication, not OAuth. Enough for a personal connector used by exactly one person, me.</p><pre>function requireBearerToken(req, res, next) {<br>  const header = req.header(&quot;authorization&quot;) ?? &quot;&quot;;<br>  const [scheme, token] = header.split(&quot; &quot;);<br><br>  if (scheme !== &quot;Bearer&quot; || token !== process.env.MCP_BEARER_TOKEN) {<br>    res.status(401).json({ error: &quot;unauthorized&quot; });<br>    return;<br>  }<br>  next();<br>}<br><br>app.post(&quot;/mcp&quot;, requireBearerToken, async (req, res) =&gt; {<br>  const server = buildServer(); // registerTool(&quot;add_job_listing&quot;, ...)<br>  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });<br>  await server.connect(transport);<br>  await transport.handleRequest(req, res, req.body);<br>});</pre><p>The server runs in stateless mode, each request creates a new McpServer instance. This choice simplifies the implementation (no session id bookkeeping needed) and is enough for a personal connector with low request volume.</p><p>The environment variables it needs, I keep in a local .env (never commit it, add it to .gitignore):</p><pre>GOOGLE_APPLICATION_CREDENTIALS=./secrets/serviceAccountKey.json<br>FIRESTORE_DATABASE_ID=labs<br>APPLYMATE_OWNER_UID=&lt;uid-from-firebase-console&gt;<br>MCP_BEARER_TOKEN=&lt;generate-with: openssl rand -hex 32&gt;<br>PORT=8787</pre><h3>Proving It Works Before Going to the Cloud</h3><pre>npm run dev<br>npx @modelcontextprotocol/inspector</pre><p>MCP Inspector opens in the browser. Connect to http://localhost:8787/mcp with the header Authorization: Bearer &lt;token&gt;, then try calling the add_job_listing tool directly from there. If a new document shows up in the Firestore Console, the flow is correct and ready for the next stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxB5th6eiML0kpg9ynq2zg.png" /><figcaption>MCP Inspector</figcaption></figure><h3>Extending the Tools: Update and Delete</h3><p>After a few weeks using add_job_listing, a new problem showed up. A listing&#39;s status changes (interview, rejected, offer), or something got typo&#39;d when I first saved it. I needed a way to update and delete those documents from chat too, instead of opening the Firestore Console manually every time.</p><p>The problem is different from just adding another tool. Where add_job_listing only needs to write a new document, update_job_listing and delete_job_listing need to know which document is meant, first. And Claude never knows the Firestore document ID from an ordinary chat, that&#39;s an implementation detail that never comes up in conversation.</p><p>The solution is one helper shared by both tools, tools/jobListingLookup.ts. It looks for the document three ways, in order of accuracy: jobListingId if already known, jobLink on an exact match, or the pair company and position if neither of the above exists.</p><pre>import { getDb } from &quot;../firebase.js&quot;;<br>import type { DocumentData, DocumentReference, Query } from &quot;firebase-admin/firestore&quot;;<br><br>export interface JobListingLookupInput {<br>  jobListingId?: string;<br>  matchJobLink?: string;<br>  matchCompany?: string;<br>  matchPosition?: string;<br>}<br>export type LookupResult =<br>  | { status: &quot;found&quot;; ref: DocumentReference; data: DocumentData }<br>  | { status: &quot;not_found&quot; }<br>  | {<br>      status: &quot;ambiguous&quot;;<br>      candidates: Array&lt;{ id: string; company: string; position: string; jobLink: string }&gt;;<br>    };<br>export async function findJobListing(<br>  ownerId: string,<br>  input: JobListingLookupInput,<br>): Promise&lt;LookupResult&gt; {<br>  const db = getDb();<br>  const collection = db.collection(&quot;job_listings&quot;);<br>  if (input.jobListingId) {<br>    const ref = collection.doc(input.jobListingId);<br>    const snap = await ref.get();<br>    if (!snap.exists || snap.data()?.ownerId !== ownerId) {<br>      return { status: &quot;not_found&quot; };<br>    }<br>    return { status: &quot;found&quot;, ref, data: snap.data() as DocumentData };<br>  }<br>  let query: Query = collection.where(&quot;ownerId&quot;, &quot;==&quot;, ownerId);<br>  if (input.matchJobLink) {<br>    query = query.where(&quot;jobLink&quot;, &quot;==&quot;, input.matchJobLink);<br>  } else if (input.matchCompany &amp;&amp; input.matchPosition) {<br>    query = query.where(&quot;company&quot;, &quot;==&quot;, input.matchCompany).where(&quot;position&quot;, &quot;==&quot;, input.matchPosition);<br>  } else {<br>    throw new Error(<br>      &quot;Butuh salah satu dari: jobListingId, matchJobLink, atau pasangan matchCompany+matchPosition.&quot;,<br>    );<br>  }<br>  const snapshot = await query.get();<br>  if (snapshot.empty) {<br>    return { status: &quot;not_found&quot; };<br>  }<br>  if (snapshot.size &gt; 1) {<br>    return {<br>      status: &quot;ambiguous&quot;,<br>      candidates: snapshot.docs.map((doc) =&gt; ({<br>        id: doc.id,<br>        company: doc.data().company,<br>        position: doc.data().position,<br>        jobLink: doc.data().jobLink,<br>      })),<br>    };<br>  }<br>  const doc = snapshot.docs[0];<br>  return { status: &quot;found&quot;, ref: doc.ref, data: doc.data() };<br>}</pre><p>The most important part is actually the ambiguous status. If the company and position mentioned in chat match more than one document, this helper doesn&#39;t just grab one at random. It returns the list of candidates, so Claude can ask me back which document is meant, instead of guessing and risking an update or delete on the wrong data.</p><p>updateJobListing.ts uses this helper to find the document, then builds a partial patch, only the fields the user actually filled in get updated, everything else in Firestore is left untouched.</p><pre>import { z } from &quot;zod&quot;;<br>import { SALARY_CURRENCIES, SALARY_PERIODS } from &quot;./salaryEnums.js&quot;;<br>import { findJobListing } from &quot;./jobListingLookup.js&quot;;<br><br>export const updateJobListingInputShape = {<br>  jobListingId: z.string().optional().describe(&quot;ID dokumen Firestore, kalau sudah tahu.&quot;),<br>  matchJobLink: z.string().optional().describe(&quot;Link loker yang sudah tersimpan, untuk mencari dokumennya.&quot;),<br>  matchCompany: z.string().optional().describe(&quot;Nama perusahaan, dipakai bareng matchPosition.&quot;),<br>  matchPosition: z.string().optional().describe(&quot;Posisi, dipakai bareng matchCompany.&quot;),<br>  company: z.string().min(1).optional(),<br>  position: z.string().min(1).optional(),<br>  jobLink: z.string().url().optional(),<br>  city: z.string().optional(),<br>  salary: z.string().optional(),<br>  salaryCurrency: z.enum(SALARY_CURRENCIES).optional(),<br>  salaryPeriod: z.enum(SALARY_PERIODS).optional(),<br>  jobDesc: z.string().optional(),<br>  jobRequirement: z.string().optional(),<br>  email: z.string().optional(),<br>  phone: z.string().optional(),<br>  note: z.string().optional(),<br>  tags: z.array(z.string()).optional(),<br>};<br>const IDENTIFIER_KEYS = [&quot;jobListingId&quot;, &quot;matchJobLink&quot;, &quot;matchCompany&quot;, &quot;matchPosition&quot;] as const;<br>export async function updateJobListing(input) {<br>  const ownerId = process.env.APPLYMATE_OWNER_UID;<br>  const lookup = await findJobListing(ownerId, input);<br>  if (lookup.status === &quot;not_found&quot;) {<br>    return { content: [{ type: &quot;text&quot;, text: &quot;Loker tidak ditemukan di Firestore.&quot; }] };<br>  }<br>  if (lookup.status === &quot;ambiguous&quot;) {<br>    const list = lookup.candidates.map((c) =&gt; `- id: ${c.id} - ${c.position} di ${c.company}`).join(&quot;\n&quot;);<br>    return { content: [{ type: &quot;text&quot;, text: `Ada ${lookup.candidates.length} loker yang cocok:\n${list}` }] };<br>  }<br>  const patch: Record&lt;string, unknown&gt; = {};<br>  for (const [key, value] of Object.entries(input)) {<br>    if (IDENTIFIER_KEYS.includes(key as any)) continue;<br>    if (value !== undefined) patch[key] = value;<br>  }<br>  await lookup.ref.update(patch);<br>  return {<br>    content: [{ type: &quot;text&quot;, text: `Loker &quot;${lookup.data.position}&quot; di ${lookup.data.company} berhasil diupdate.` }],<br>  };<br>}</pre><p>deleteJobListing.ts is simpler, it just needs an identifier to find the document through the same helper, then deletes it.</p><pre>import { findJobListing } from &quot;./jobListingLookup.js&quot;;<br><br>export async function deleteJobListing(input) {<br>  const ownerId = process.env.APPLYMATE_OWNER_UID;<br>  const lookup = await findJobListing(ownerId, input);<br>  if (lookup.status === &quot;not_found&quot;) {<br>    return { content: [{ type: &quot;text&quot;, text: &quot;Loker tidak ditemukan di Firestore.&quot; }] };<br>  }<br>  if (lookup.status === &quot;ambiguous&quot;) {<br>    const list = lookup.candidates.map((c) =&gt; `- id: ${c.id} - ${c.position} di ${c.company}`).join(&quot;\n&quot;);<br>    return { content: [{ type: &quot;text&quot;, text: `Ada ${lookup.candidates.length} loker yang cocok:\n${list}` }] };<br>  }<br>  const { company, position } = lookup.data;<br>  await lookup.ref.delete();<br>  return { content: [{ type: &quot;text&quot;, text: `Loker &quot;${position}&quot; di ${company} berhasil dihapus.` }] };<br>}</pre><p>One small closing note for this section: the SALARY_CURRENCIES and SALARY_PERIODS constants, which used to be inline in addJobListing.ts, are now moved into their own tools/salaryEnums.ts, so that addJobListing and updateJobListing always use the exact same list of currencies and salary periods, no risk of the two tools drifting apart because one of them didn&#39;t get updated. Once all three tools are registered in index.ts, Claude&#39;s connection to my server now shows three tools at once, add_job_listing, update_job_listing, and delete_job_listing.</p><h3>Why Credentials Are Explosive Material</h3><p>Before pushing to GitHub, make sure .gitignore actually holds back the credentials file. Firebase service account filenames follow the pattern &lt;project-id&gt;-firebase-adminsdk-&lt;hash&gt;.json, so the match needs to be a substring, not a prefix:</p><pre>node_modules/<br>dist/<br>.env<br><br>serviceAccountKey.json<br>*service-account*.json<br>*firebase-adminsdk*.json<br>*.json.key<br># belt and suspenders: block every .json at the root except the project&#39;s own config files<br>/*.json<br>!/package.json<br>!/package-lock.json<br>!/tsconfig.json</pre><p>I’m emphasizing this because I went through it myself. While working on this project, my service account key accidentally got committed in the first push. Luckily it was caught immediately, and I rotated the key (generated a new one, disabled the old one) within minutes. But the lesson stays the same: once a credentials file lands in git history, treat it as already leaked. Rotate it, don’t just delete the commit.</p><h3>Pushing It Up: GitHub, Then Railway</h3><pre>git init<br>git add .<br>git commit -m &quot;Initial commit&quot;<br>git remote add origin &lt;https://github.com/&gt;&lt;username&gt;/&lt;repo&gt;.git<br>git push -u origin main</pre><p>For hosting, I chose <a href="https://railway.com/">Railway</a>, over <a href="https://render.com/">Render</a> (cold start issues on the free tier) and <a href="http://fly.io/">Fly.io</a> (more complex setup than this simple use case needs).</p><ol><li>Create an account at <a href="http://railway.app/">railway.app</a>, sign up with GitHub.</li><li>New Project, then Deploy from GitHub repo.</li><li>If your repo doesn’t show up in the search, this is what happened to me and took a while to realize: a Railway account can be connected to GitHub only through OAuth login (identity verification), while Railway’s GitHub App hasn’t actually been installed, which is what actually grants read access to the repo. Check at <a href="http://github.com/settings/installations">github.com/settings/installations</a>. If Railway isn&#39;t listed there, go back to Railway, look for Configure GitHub App or reconnect GitHub on the New Project page, then pick the repo you want to grant access to (or All repositories).</li><li>Once the repo is detected, click to deploy. Railway automatically detects a Node.js project and runs npm install, then npm run build, then npm start.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjGA-RyAw94C_GI7J_Yu8Q.png" /><figcaption>ApplyMate MCP Deployed Through Railway</figcaption></figure><h3>Filling In the Variables That Actually Bring It to Life</h3><p>In the Railway service, go to the Variables tab, add:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*UG6ZIKcEPZECmj4gDOxMmg.png" /></figure><p>To copy the JSON content into a single line without formatting issues, the easiest way is through the terminal:</p><pre>cat serviceAccountKey.json | pbcopy   # macOS</pre><p>then paste it straight into the variable’s value.</p><p>Why GOOGLE_APPLICATION_CREDENTIALS_JSON, instead of a file path? Because PaaS platforms like Railway don&#39;t have a persistent filesystem you can fill manually before the container starts. The most common solution: put the JSON file&#39;s content directly as an environment variable, then your code (firebase.ts above) reads it and calls JSON.parse() on that string at runtime.</p><p>Once all the variables are set, Railway automatically redeploys.</p><p>One last step: by default, a Railway service is Unexposed, with no public URL yet. Go to the Settings tab, find the Networking section, click Generate Domain. You’ll get a free domain in the format xxxxx.up.railway.app.</p><h3>Connecting It to Claude</h3><ol><li>Open <a href="http://claude.ai/">claude.ai</a>, go to Settings, then Connectors, then Add custom connector</li><li>Fill in any Name (for example ApplyMate MCP) and the URL https://&lt;your-railway-domain&gt;/mcp</li><li>In the Authentication section, since this server uses a static bearer token, not real OAuth, choose No sign in. This option is for servers using an API key/token, not an OAuth flow.</li><li>Scroll to Request headers, add a header name Authorization with the value Bearer &lt;your-MCP_BEARER_TOKEN&gt; (note the space after the word Bearer), then check Required.</li><li>Save or Connect.</li></ol><p>Claude automatically detects all three tools registered on the server, add_job_listing, update_job_listing, and delete_job_listing, complete with their descriptions and input schemas, without me needing any extra configuration on Claude&#39;s side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DynjYYKY7B2EAhHTAJvsoA.png" /><figcaption>Connector Setup</figcaption></figure><h3>The Proof Moment: Real Data in Firestore</h3><p>I open a new chat, paste in one job listing’s description, and ask Claude to save it. After approving the tool call, I check the Firebase Console, Firestore, the labs database, the job_listings collection. A new document shows up there, complete with every field I filled in through ordinary chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTB-DOhhQcgBJpmEyGDjrA.png" /><figcaption>Firestore Result</figcaption></figure><p>Once I was confident the flow was correct, I tried something heavier: re-importing some job applications from the current month, previously logged by hand in Notion, straight into Firestore through Claude, in a single chat session. Everything went in without a single failure.</p><h3>What’s Changed, and What Hasn’t</h3><p><strong>What’s working:</strong> Claude can write, update, and delete Firestore documents with a single chat command each, replacing the manual copy-paste process I did for months.</p><p><strong>What isn’t yet:</strong> the Android side. Firestore supports real time sync through snapshot listeners, but that only activates if the app attaches a listener to the job_listings collection. The ApplyMate variant that reads this data (I call it ApplyMate Lab) is currently in progress, being updated to match the response shape the Firestore side now writes, but it hasn&#39;t shipped yet. So for now, the flow is more like an ordinary request response API: my server waits (await) for write confirmation from Firestore before replying to Claude, not a connection that stays open.</p><p>From here, this MCP server becomes a foundation I can keep developing further for other workflows I use every day. But even with just these three tools like now, one chat command has already been enough to change how I work every day.</p><p>If you’re building something similar, two of the most valuable lessons from this project:</p><ol><li>Always treat a credentials file as explosive material. A strict .gitignore is mandatory, not optional.</li><li>When troubleshooting integration between platforms (Railway and GitHub in my case), suspect the App installation or permission layer first, before blaming the repo name or its visibility.</li></ol><h3>References</h3><ul><li>Model Context Protocol, official spec: <a href="https://modelcontextprotocol.io/">modelcontextprotocol.io</a></li><li>Cloud Firestore, named database documentation: <a href="https://firebase.google.com/docs/firestore">firebase.google.com/docs/firestore</a></li><li>Railway, deploy from GitHub documentation: <a href="https://docs.railway.app/">docs.railway.app</a></li><li>Render: <a href="https://render.com/">https://render.com/</a></li><li>Fly.io: <a href="https://fly.io/">https://fly.io/</a></li><li>Firebase Admin SDK for Node.js: <a href="https://firebase.google.com/docs/admin/setup">firebase.google.com/docs/admin/setup</a></li><li>ApplyMate: <a href="https://play.google.com/store/apps/details?id=id.yumtaufikhidayat.applymate">https://play.google.com/store/apps/details?id=id.yumtaufikhidayat.applymate</a></li><li>Notion MCP: <a href="https://developers.notion.com/guides/mcp/overview">https://developers.notion.com/guides/mcp/overview</a></li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9QTaaaxboQP_gKSLedW_w.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p><strong>Disclosure:</strong> This post includes affiliate and partnership links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f7fc9f24c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/from-chat-to-database-building-my-own-mcp-server-for-claude-a4f7fc9f24c0">From Chat to Database: Building My Own MCP Server for Claude</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust: Every try-catch You’ve Ever Written Was a Promise You Could Break, Result Isn’t]]></title>
            <link>https://blog.stackademic.com/rust-every-try-catch-youve-ever-written-was-a-promise-you-could-break-result-isn-t-25f633f390e8?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/25f633f390e8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 04:12:07 GMT</pubDate>
            <atom:updated>2026-08-07T06:52:00.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YK6mM42QiBHxkC6yG9EXxw.png" /><figcaption>Exception: One hides the failure. The other forces you to face it.</figcaption></figure><p>Every Android engineer has shipped this without thinking twice about it.</p><pre>fun getUser(id: String): User {<br>    val response = api.fetchUser(id) // might throw<br>    return response.toUser()<br>}<br><br>fun main() {<br>    val user = getUser(&quot;123&quot;) // compiles fine, crashes at runtime<br>    println(user.name)<br>}</pre><p>This compiles. Ship it, and somewhere in production, fetchUser throws an IOException nobody catches, and the app dies. The compiler never warned you. It never had to. throws in Kotlin is a suggestion, not a rule.</p><pre>fn get_user(id: &amp;str) -&gt; Result&lt;User, ApiError&gt; {<br>    let response = api::fetch_user(id)?; // might fail<br>    Ok(response.to_user())<br>}<br><br>fn main() {<br>    let user = get_user(&quot;123&quot;); // Result&lt;User, ApiError&gt;, not User<br>    println!(&quot;{}&quot;, user.unwrap().name); // compiler forces you to unwrap it first<br>}</pre><p>This also compiles, but only because main was forced to acknowledge that get_user might fail. You can&#39;t print user.name directly. user isn&#39;t a User, it&#39;s a Result&lt;User, ApiError&gt;, a value that is either Ok(User) or Err(ApiError), and the compiler will not let you touch what&#39;s inside until you say which one you&#39;re dealing with.</p><p>In <a href="https://yumtaufikhidayat.medium.com/youve-been-using-enums-wrong-your-whole-career-rust-is-here-to-prove-it-4fa8dbb3b746">Part 6</a>, we talked about how Option&lt;T&gt; kills null at compile time. Turns out that&#39;s just half the story. Rust applies the exact same trick to something bigger: the entire concept of &quot;this operation might fail.&quot; No exceptions, no try, no catch. Just a return type that tells the truth.</p><h3>A Type That Tells the Truth</h3><p>Rust has no exception mechanism. There’s no throw, no try-catch, no stack unwinding for normal error flow. Every function that can fail says so in its signature, Result&lt;T, E&gt;, and the caller can&#39;t touch what&#39;s inside without opening it first, through match, ?, or an explicit .unwrap().</p><h3>The Developer This Changes First</h3><p>Android engineers who’ve written try { } catch (e: Exception) { } more times than they&#39;d like to admit. Especially the ones who&#39;ve caught a generic Exception, logged it, and moved on without really knowing what just happened or whether the app is still in a valid state.</p><h3>Where the Compiler Goes Quiet</h3><p>The moment this becomes personal is the moment an app crashes in production from an exception nobody planned for. Maybe it was an unchecked exception the type system never asked you to handle. Maybe it was a checked one you caught, logged, and silently swallowed, letting the app limp forward in a broken state instead of failing loudly. Either way, the compiler said nothing. It couldn’t. Kotlin’s checked exceptions are a JVM-level convention, not something the Kotlin compiler enforces the way it enforces null-safety.</p><p>Rust doesn’t give you that option. If get_user can fail, Result&lt;User, ApiError&gt; is baked into its signature, and every caller has to open that box before touching what&#39;s inside.</p><h3>Three Levels In</h3><h4>Level 1: Result&lt;T, E&gt;, the two-branch box</h4><pre>enum Result&lt;T, E&gt; {<br>    Ok(T),<br>    Err(E),<br>}</pre><p>That’s it. That’s the whole mechanism. Result is an enum with exactly two variants, Ok holding a success value, Err holding an error value. No inheritance hierarchy, no checked-vs-unchecked distinction, no Throwable supertype. Just two boxes, and the compiler needs you to open the right one.</p><pre>fn divide(a: f64, b: f64) -&gt; Result&lt;f64, String&gt; {<br>    if b == 0.0 {<br>        return Err(&quot;cannot divide by zero&quot;.to_string());<br>    }<br>    Ok(a / b)<br>}<br><br>fn main() {<br>    match divide(10.0, 2.0) {<br>        Ok(result) =&gt; println!(&quot;Result:{}&quot;, result),<br>        Err(e) =&gt; println!(&quot;Error:{}&quot;, e),<br>    }<br>}</pre><p>Same exhaustive match from Part 6. Miss the Err arm, the code doesn&#39;t compile. There&#39;s no code path where a failed division silently becomes a NaN or a crash three functions downstream. The failure is visible at the exact point where it happened.</p><h4>Level 2: ?, propagation without the boilerplate</h4><p>Matching every single Result gets old fast, especially when a function just wants to pass the error up the chain instead of handling it locally. That&#39;s what ? is for.</p><pre>fn get_user_email(id: &amp;str) -&gt; Result&lt;String, ApiError&gt; {<br>    let response = api::fetch_user(id)?;<br>    let user = response.to_user()?;<br>    Ok(user.email)<br>}</pre><p>Each ? says: if this is Ok(value), unwrap it and keep going. If it&#39;s Err(e), stop right here and return that Err from the whole function. No catch, no throw, no exception bubbling up through five stack frames you didn&#39;t write and don&#39;t control. The function signature already told you get_user_email returns Result&lt;String, ApiError&gt;, so ? is just doing what the type already promised.</p><p>Compare that to Kotlin. There’s no language-level equivalent. The closest is manually checking and re-throwing, or reaching for a Result-like wrapper class (Kotlin does have a kotlin.Result, but it&#39;s opt-in, and most codebases still lean on exceptions underneath it).</p><h4>Level 3: custom error types and combinators</h4><p>Real apps don’t fail with one error shape. A network call and a JSON parse fail differently, and lumping them into String errors (like the divide example) throws away information. This is where enum from Part 6 comes back.</p><pre>enum ApiError {<br>    Network(String),<br>    Parse(String),<br>    NotFound,<br>}<br><br>fn fetch_user(id: &amp;str) -&gt; Result&lt;Response, ApiError&gt; {<br>    let response = http_get(id).map_err(|e| ApiError::Network(e.to_string()))?;<br>    if response.status == 404 {<br>        return Err(ApiError::NotFound);<br>    }<br>    Ok(response)<br>}</pre><p>ApiError is an exhaustive, closed set of everything that can go wrong in this domain. match on it later, and the compiler will remind you if a new variant shows up and you forgot to handle it. Try doing that with a Kotlin exception hierarchy and an open class you don&#39;t control.</p><p>A few combinators worth knowing, since they show up constantly once you’re past the basics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLpEjCdhFWvtE-_5i5d7dw.png" /></figure><h3>The Envelope Analogy</h3><p>Think of every function call as sending a job application. Option&lt;T&gt; from Part 6 was about whether you get a reply at all, Some(offer) or None. Result&lt;T, E&gt; is different. You always get a reply, but it&#39;s a sealed envelope, and it&#39;s either an offer letter or a rejection letter that names the reason.</p><p>An exception is more like the recruiter grabbing your resume, deciding to walk over to your desk, and yelling the rejection at you whenever they feel like it, sometimes seconds later, sometimes three interviews down the line, in a room where nobody was told to expect it. Result&lt;T, E&gt; puts the answer in your hand immediately, in a format you&#39;re required to open. You can&#39;t accidentally misplace the envelope. The compiler won&#39;t let the function return until you&#39;ve decided what happens with what&#39;s inside.</p><h3>The Impacts</h3><h4>Technical</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XkVz32w0P_LO9iSv904cA.png" /></figure><p>Google’s own Android documentation states that <a href="https://developer.android.com/topic/performance/vitals/crash">null pointer exceptions are the largest single cause of app crashes on Google Play</a>, the exact failure mode Part 6 covered. Unhandled and mishandled exceptions in general follow the same pattern: a class of runtime failure that Rust converts into a compile-time obligation.</p><h4>Business</h4><p>Software defects aren’t a rounding error. The Consortium for Information &amp; Software Quality’s 2022 report puts <a href="https://www.perforce.com/blog/pdx/cost-of-software-defects">software defects at roughly $607 billion in cost to U.S. businesses in 2022 alone</a>, part of a broader <a href="https://www.it-cisq.org/press-releases/12-06-22/">$2.41 trillion cost of poor software quality in the US</a> that year. That number covers everything from technical debt to supply chain issues, but unhandled and mishandled errors sit right in the middle of it, since they’re the failures that make it past code review and into production.</p><p>On mobile specifically, the cost shows up as churn. Industry research puts <a href="https://globalbit.co.il/blog/cost-software-bugs-production-2026">around 70% of users who experience a mobile app crash uninstalling within 48 hours and not coming back</a>. Google Play treats this seriously enough to gate app visibility on it: apps that cross Play’s crash-rate bad-behavior threshold get less discoverability in the Play Store.</p><p>None of this means Rust makes bugs impossible. Business logic can still be wrong even when every Result is handled. What Rust removes is a specific, well-documented category, the failure that exists because a function could return an error and nothing forced anyone to check.</p><h3>Wrapping Up</h3><p>Result&lt;T, E&gt; isn&#39;t really about eliminating errors. It&#39;s about refusing to let an error travel through your program unacknowledged. Ok says the value is safe to use. Err says here&#39;s exactly what went wrong, and here&#39;s the type that proves it. There&#39;s no third option where the function just... doesn&#39;t tell you.</p><p>match says: handle both branches, right here, or the code doesn&#39;t compile. ? says: propagate the failure upward, explicitly, one function signature at a time. Custom error enums say: every way this operation can fail is a closed, known set, not an open hierarchy you&#39;re hoping you&#39;ve covered.</p><p>Put together, these three pieces turn “might fail” from a runtime gamble into a compile-time contract. No exception sneaking past a bare catch (e: Exception). No crash three stack frames away from where the real problem started. No error that exists only in a log line nobody reads until after the incident.</p><p>map_err, and_then, unwrap_or, none of these mutate self. Each one takes a value, does something to it, and hands back a new value, chained one after another. That shape should feel familiar. It&#39;s the same shape as .let {}, .also {}, .apply {}, Kotlin&#39;s scope functions, except Rust gets there through plain functions on Result instead of a dedicated language feature. Same instinct, different plumbing. That&#39;s Part 8.</p><h3>References</h3><ol><li>Android Developers, <a href="https://developer.android.com/topic/performance/vitals/crash">“Crashes | App quality”</a>, on null pointer exceptions as the largest cause of Google Play app crashes</li><li>Consortium for Information &amp; Software Quality (CISQ), <a href="https://www.it-cisq.org/press-releases/12-06-22/">Cost of Poor Software Quality in the US: A 2022 Report, press release</a></li><li>Perforce, <a href="https://www.perforce.com/blog/pdx/cost-of-software-defects">“The Real Cost of Software Defects”</a>, citing the CISQ 2022 figure of $607 billion in software defect costs</li><li>Globalbit, <a href="https://globalbit.co.il/blog/cost-software-bugs-production-2026">“The Real Cost of Software Bugs in Production (2026 Data)”</a>, on the 70% mobile app uninstall rate after a crash</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25f633f390e8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rust-every-try-catch-youve-ever-written-was-a-promise-you-could-break-result-isn-t-25f633f390e8">Rust: Every try-catch You’ve Ever Written Was a Promise You Could Break, Result Isn’t</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’ve Been Using Enums Wrong Your Whole Career. Rust Is Here to Prove It.]]></title>
            <link>https://blog.stackademic.com/youve-been-using-enums-wrong-your-whole-career-rust-is-here-to-prove-it-4fa8dbb3b746?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa8dbb3b746</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 12:00:45 GMT</pubDate>
            <atom:updated>2026-06-12T02:17:30.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTfJLjas6N7ZCeX8zG2iIA.png" /><figcaption>Enum, Match, and Option in Rust</figcaption></figure><p>You’ve probably written something like this in Kotlin before:</p><pre>enum class NetworkState {<br>    LOADING,<br>    SUCCESS,<br>    ERROR<br>}<br><br>fun handleState(state: NetworkState) {<br>    when (state) {<br>        NetworkState.LOADING -&gt; showLoading()<br>        NetworkState.SUCCESS -&gt; showContent()<br>        NetworkState.ERROR -&gt; showError()<br>    }<br>}</pre><p>It works. It’s readable. It feels complete.</p><p>Now look at both versions, side by side:</p><pre>// Kotlin<br>enum class NetworkState {<br>    LOADING,<br>    SUCCESS,<br>    ERROR<br>}<br><br>fun handleState(state: NetworkState) {<br>    when (state) {<br>        NetworkState.LOADING  -&gt; showLoading()<br>        NetworkState.SUCCESS  -&gt; showContent()   // but which content?<br>        NetworkState.ERROR    -&gt; showError()     // but which error?<br>    }<br>}</pre><pre>// Rust<br>enum NetworkState {<br>    Loading,<br>    Success(String),     // carries the actual content<br>    Error(String),       // carries the actual error message<br>}<br><br>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading        =&gt; show_loading(),<br>        NetworkState::Success(data)  =&gt; show_content(data),<br>        NetworkState::Error(msg)     =&gt; show_error(msg),<br>    }<br>}</pre><p>Don’t try to explain the difference yet. Just feel it.</p><p>The Kotlin version names the states, the Rust version names the states <em>and carries the data that belongs to each state</em>, and match doesn&#39;t just route execution to a branch but it unpacks the data right there, inline.</p><p>That’s the gap this article closes.</p><h3>More Than Named Constants</h3><p>In Kotlin, enum class is fundamentally a set of named constants. You can attach properties and functions to them, but every variant shares the same structure. If SUCCESS needs a data field and ERROR needs a message field, you&#39;re fighting against the tool. That&#39;s exactly why sealed class was invented: a separate construct for variants that need different shapes.</p><p>Rust doesn’t make that distinction. Its enum handles both jobs.</p><p>The technical term for this is <strong>algebraic data type</strong>, which sounds academic but the concept is straightforward.</p><p>Think of it like a food delivery order.</p><p>Kotlin’s enum class is a menu where every item comes in the same box with the same dimensions. You can label them differently (Nasi Goreng, Mie Ayam, Soto), but structurally they&#39;re identical. One size, same packaging across the board.</p><p>Rust’s enum is a menu where every item can arrive differently. Nasi Goreng comes on a plate with crackers on the side. Mie Ayam comes in a bowl with the soup separate. Soto comes in a cup with a portion of rice. Same menu, completely different contents per item.</p><p>That’s what “algebraic data type” means in practice: a type that can be <em>one of several things</em>, and each <em>thing</em> can carry <em>different data</em>.</p><pre>enum MenuItem {<br>    NasiGoreng { plate: String, crackers: u8 },<br>    MieAyam { bowl: String, soup_ml: u32 },<br>    Soto { cup: String, rice_grams: u32 },<br>}</pre><p>In Kotlin, modeling this requires a sealed class with three separate data class variants. In Rust, it&#39;s one enum. No second construct. No extra ceremony.</p><h3>The Developer This Changes First</h3><p>Three groups run into this immediately.</p><ol><li><strong>Android developers who already use sealed class for UI state.</strong> <br>If you’ve written sealed class UiState&lt;T&gt; with Loading, Success(val data: T), and Error(val message: String), you&#39;re already thinking in algebraic data types. Rust just collapses that pattern into a single enum, without needing a second construct to make it work.</li><li><strong>Developers who’ve crashed an app because of a NullPointerException.<br></strong>Rust doesn’t have null. But it has something better, and understanding Rust’s enum is the prerequisite for understanding why Option&lt;T&gt; is the solution, not a workaround.</li><li><strong>Anyone who’s written </strong><strong>!! in Kotlin and felt a little nervous about it.</strong></li></ol><p>The !! operator, sometimes called the <em>double bang</em> or the <em>non-null assertion operator,</em> is Kotlin&#39;s way of letting you say &quot;trust me, this is not null.&quot; The compiler accepts it. But if you&#39;re wrong at runtime, the app throws a NullPointerException and crashes. The !! is essentially a pinky promise between you and the runtime, and the runtime doesn&#39;t care if you were wrong.</p><p>Every !! is a bet. Sometimes you win, sometimes you wake up to a 1-star review.</p><p>Rust removes the contract entirely. There’s no null to assert against, and there’s no !! to write. The mechanism that makes this possible is enum, specifically Option&lt;T&gt;.</p><p><strong>Developers who’ve already used </strong><strong>Option&lt;T&gt; or </strong><strong>Result&lt;T, E&gt; but treated them like nullable types.</strong> These are not nullable types, they&#39;re enums. Understanding the difference changes how you read error messages, write APIs, and think about state.</p><h3>Four Signals You Need This</h3><p>The first signal: you have state that can be more than one shape. Loading, success with data, error with a message. In Kotlin you reach for sealed class. In Rust you reach for enum.</p><p>The second signal: you need to represent a value that might not exist, without using null. Not “it’s null until it loads.” Not “it could be null, check before use.” A value that is <em>explicitly either present or absent</em>, and the compiler forces you to handle both.</p><p>The third signal: you’ve written else -&gt; { /* this shouldn&#39;t happen */ } inside a when block. That comment is a smell. It means you&#39;re relying on your own memory to maintain completeness. Rust match turns that into a compile error. You can&#39;t forget a case because the compiler won&#39;t let you ship until every variant is handled.</p><p>The fourth signal: you want to eliminate an entire category of runtime bugs before the program runs. Not reduce them. Eliminate them.</p><h3>A Language That Doesn’t Trust You (And That’s the Point)</h3><p>Kotlin’s split between enum class and sealed class is not a design flaw. It&#39;s a pragmatic decision shaped by the JVM. The JVM has its own type system constraints, and Kotlin works within those boundaries while giving you a good experience on top.</p><p>Rust has no JVM. It compiles directly to machine code, which means the language designers could make different choices. One of those choices: no separate enum and sealed class. One construct, full power.</p><p>But the more important design decision is about match.</p><p>In Kotlin, when is exhaustive only when it&#39;s used as an expression:</p><pre>// Kotlin forces exhaustiveness here because when is used as an expression<br>val result = when (state) {<br>    is UiState.Loading  -&gt; handleLoading()<br>    is UiState.Success  -&gt; handleSuccess(state.data)<br>    is UiState.Error    -&gt; handleError(state.message)<br>}</pre><p>Use it as a statement, and you can silently skip branches:</p><pre>// Kotlin doesn&#39;t stop you from forgetting a variant here<br>when (state) {<br>    is UiState.Success -&gt; handleSuccess(state.data)<br>    // Loading and Error? Compiler doesn&#39;t care.<br>}</pre><p>Rust match is always exhaustive. There is no version that lets you skip a variant. Every branch must be handled, or the code does not compile. Not a warning. Not a lint suggestion. A hard error.</p><pre>match state {<br>    UiState::Loading        =&gt; handle_loading(),<br>    UiState::Success(data)  =&gt; handle_success(data),<br>    // if Error is missing: rustc refuses to compile, full stop<br>}</pre><p>This is a philosophical position. Rust doesn’t trust that developers will always remember. So it doesn’t give them the option to forget.</p><p>Option&lt;T&gt; is the same philosophy applied to null. Null doesn&#39;t exist in Rust. The concept of &quot;a value that might not be there&quot; is represented by Option&lt;T&gt;, an enum with two variants: Some(T) when the value exists, None when it doesn&#39;t. And because it&#39;s an enum handled by match, you cannot access the value without acknowledging that it might be absent.</p><p>There is no !!. There is no &quot;trust me.&quot; The language doesn&#39;t offer the option.</p><h3>From Kotlin to Rust, One Step at a Time</h3><p>Three levels, building toward Option&lt;T&gt;.</p><h3>Level 1: Basic Enum with Match</h3><p>Start with what you already know. A network request has three possible states.</p><pre>enum NetworkState {<br>    Loading,<br>    Success,<br>    Error,<br>}<br><br>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading  =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success  =&gt; println!(&quot;Data loaded&quot;),<br>        NetworkState::Error    =&gt; println!(&quot;Something went wrong&quot;),<br>    }<br>}</pre><p>Now intentionally remove one branch:</p><pre>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading  =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success  =&gt; println!(&quot;Data loaded&quot;),<br>        // NetworkState::Error is missing<br>    }<br>}</pre><p>The compiler’s response:</p><pre>error[E0004]: non-exhaustive patterns: `NetworkState::Error` not covered<br> --&gt; src/main.rs:8:11<br>  |<br>8 |     match state {<br>  |           ^^^^^ pattern `NetworkState::Error` not covered</pre><p>This is not a warning. This is the build failing. The case you tried to skip is now a compile error. That else -&gt; { /* shouldn&#39;t happen */ } comment you wrote in Kotlin? Here you can&#39;t hide behind it.</p><h3>Level 2: Enum with Data per Variant</h3><p>This is where Rust’s enum separates from both Kotlin’s enum class and its sealed class. Each variant can carry its own data, with its own type, with no extra constructs needed.</p><pre>enum NetworkState {<br>    Loading,<br>    Success(String),     // carries the response body<br>    Error(u16, String),  // carries the HTTP status code and the error message<br>}<br><br>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading              =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success(body)        =&gt; println!(&quot;Response: {}&quot;, body),<br>        NetworkState::Error(code, msg)     =&gt; println!(&quot;Error {}: {}&quot;, code, msg),<br>    }<br>}</pre><p>The Success(body) and Error(code, msg) syntax is destructuring happening directly inside the match arm. You&#39;re not just routing to a branch but also you&#39;re pulling the data out of the variant at the same time, in the same line.</p><p>Compare this with the Kotlin equivalent:</p><pre>sealed class NetworkState {<br>    object Loading : NetworkState()<br>    data class Success(val body: String) : NetworkState()<br>    data class Error(val code: Int, val message: String) : NetworkState()<br>}<br><br>fun handleState(state: NetworkState) {<br>    when (state) {<br>        is NetworkState.Loading  -&gt; println(&quot;Loading...&quot;)<br>        is NetworkState.Success  -&gt; println(&quot;Response: ${state.body}&quot;)<br>        is NetworkState.Error    -&gt; println(&quot;Error ${state.code}: ${state.message}&quot;)<br>    }<br>}</pre><p>Same intent. But Kotlin needs two constructs (sealed class + data class) to do what Rust handles with one. And the Kotlin when above is only exhaustive because the compiler infers the expression context. Change it to a statement, add a new variant later, and the compiler might not stop you. The Rust version doesn&#39;t need that vigilance, the contract is enforced structurally.</p><p>For Android developers working with UiState&lt;T&gt;, the translation is direct:</p><pre>// Kotlin<br>sealed class UiState&lt;T&gt; {<br>    object Loading : UiState&lt;Nothing&gt;()<br>    data class Success&lt;T&gt;(val data: T) : UiState&lt;T&gt;()<br>    data class Error(val message: String) : UiState&lt;Nothing&gt;()<br>}</pre><pre>// Rust<br>enum UiState&lt;T&gt; {<br>    Loading,<br>    Success(T),<br>    Error(String),<br>}</pre><p>One enum. No sealed. No Nothing. Same semantics, less ceremony.</p><h3>The Developer This Changes First</h3><p>Three groups run into this immediately.</p><ol><li><strong>Android developers who already use sealed class for UI state.</strong> If you’ve written sealed class UiState&lt;T&gt; with Loading, Success(val data: T), and Error(val message: String), you&#39;re already thinking in algebraic data types. Rust just collapses that pattern into a single enum, without needing a second construct to make it work.</li><li><strong>Developers who’ve crashed an app because of a NullPointerException.</strong> Rust doesn’t have null. But it has something better, and understanding Rust’s enum is the prerequisite for understanding why Option&lt;T&gt; is the solution, not a workaround.</li><li><strong>Anyone who’s written </strong><strong>!! in Kotlin and felt a little nervous about it.</strong></li></ol><p>The !! operator, sometimes called the <em>double bang</em> or the <em>non-null assertion operator,</em> is Kotlin&#39;s way of letting you say &quot;trust me, this is not null.&quot; The compiler accepts it. But if you&#39;re wrong at runtime, the app throws a NullPointerException and crashes. The !! is essentially a pinky promise between you and the runtime, and the runtime doesn&#39;t care if you were wrong.</p><p>Every !! is a bet. Sometimes you win, sometimes you wake up to a 1-star review.</p><p>Rust removes the contract entirely. There’s no null to assert against, and there’s no !! to write. The mechanism that makes this possible is enum, specifically Option&lt;T&gt;.</p><p><strong>Developers who’ve already used </strong><strong>Option&lt;T&gt; or </strong><strong>Result&lt;T, E&gt; but treated them like nullable types.</strong> These are not nullable types, they&#39;re enums. Understanding the difference changes how you read error messages, write APIs, and think about state.</p><h3>Four Signals You Need This</h3><p>The first signal: you have state that can be more than one shape. Loading, success with data, error with a message. In Kotlin you reach for sealed class. In Rust you reach for enum.</p><p>The second signal: you need to represent a value that might not exist, without using null. Not “it’s null until it loads.” Not “it could be null, check before use.” A value that is <em>explicitly either present or absent</em>, and the compiler forces you to handle both.</p><p>The third signal: you’ve written else -&gt; { /* this shouldn&#39;t happen */ } inside a when block. That comment is a smell. It means you&#39;re relying on your own memory to maintain completeness. Rust match turns that into a compile error. You can&#39;t forget a case because the compiler won&#39;t let you ship until every variant is handled.</p><p>The fourth signal: you want to eliminate an entire category of runtime bugs before the program runs. Not reduce them. Eliminate them.</p><h3>A Language That Doesn’t Trust You (And That’s the Point)</h3><p>Kotlin’s split between enum class and sealed class is not a design flaw. It&#39;s a pragmatic decision shaped by the JVM. The JVM has its own type system constraints, and Kotlin works within those boundaries while giving you a good experience on top.</p><p>Rust has no JVM. It compiles directly to machine code, which means the language designers could make different choices. One of those choices: no separate enum and sealed class. One construct, full power.</p><p>But the more important design decision is about match.</p><p>In Kotlin, when is exhaustive only when it&#39;s used as an expression:</p><pre>// Kotlin forces exhaustiveness here because when is used as an expression<br>val result = when (state) {<br>    is UiState.Loading  -&gt; handleLoading()<br>    is UiState.Success  -&gt; handleSuccess(state.data)<br>    is UiState.Error    -&gt; handleError(state.message)<br>}</pre><p>Use it as a statement, and you can silently skip branches:</p><pre>// Kotlin doesn&#39;t stop you from forgetting a variant here<br>when (state) {<br>    is UiState.Success -&gt; handleSuccess(state.data)<br>    // Loading and Error? Compiler doesn&#39;t care.<br>}</pre><p>Rust match is always exhaustive. There is no version that lets you skip a variant. Every branch must be handled, or the code does not compile. Not a warning. Not a lint suggestion. A hard error.</p><pre>match state {<br>    UiState::Loading        =&gt; handle_loading(),<br>    UiState::Success(data)  =&gt; handle_success(data),<br>    // if Error is missing: rustc refuses to compile, full stop<br>}</pre><p>This is a philosophical position. Rust doesn’t trust that developers will always remember. So it doesn’t give them the option to forget.</p><p>Option&lt;T&gt; is the same philosophy applied to null. Null doesn&#39;t exist in Rust. The concept of &quot;a value that might not be there&quot; is represented by Option&lt;T&gt;, an enum with two variants: Some(T) when the value exists, None when it doesn&#39;t. And because it&#39;s an enum handled by match, you cannot access the value without acknowledging that it might be absent.</p><p>There is no !!. There is no &quot;trust me.&quot; The language doesn&#39;t offer the option.</p><h3>From Kotlin to Rust, One Step at a Time</h3><p>Three levels, building toward Option&lt;T&gt;.</p><h3>Level 1: Basic Enum with Match</h3><p>Start with what you already know. A network request has three possible states.</p><pre>enum NetworkState {<br>    Loading,<br>    Success,<br>    Error,<br>}<br><br>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading  =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success  =&gt; println!(&quot;Data loaded&quot;),<br>        NetworkState::Error    =&gt; println!(&quot;Something went wrong&quot;),<br>    }<br>}</pre><p>Now intentionally remove one branch:</p><pre>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading  =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success  =&gt; println!(&quot;Data loaded&quot;),<br>        // NetworkState::Error is missing<br>    }<br>}</pre><p>The compiler’s response:</p><pre>error[E0004]: non-exhaustive patterns: `NetworkState::Error` not covered<br> --&gt; src/main.rs:8:11<br>  |<br>8 |     match state {<br>  |           ^^^^^ pattern `NetworkState::Error` not covered</pre><p>This is not a warning. This is the build failing. The case you tried to skip is now a compile error. That else -&gt; { /* shouldn&#39;t happen */ } comment you wrote in Kotlin? Here you can&#39;t hide behind it.</p><h3>Level 2: Enum with Data per Variant</h3><p>This is where Rust’s enum separates from both Kotlin’s enum class and its sealed class. Each variant can carry its own data, with its own type, with no extra constructs needed.</p><pre>enum NetworkState {<br>    Loading,<br>    Success(String),     // carries the response body<br>    Error(u16, String),  // carries the HTTP status code and the error message<br>}<br><br>fn handle_state(state: NetworkState) {<br>    match state {<br>        NetworkState::Loading              =&gt; println!(&quot;Loading...&quot;),<br>        NetworkState::Success(body)        =&gt; println!(&quot;Response: {}&quot;, body),<br>        NetworkState::Error(code, msg)     =&gt; println!(&quot;Error {}: {}&quot;, code, msg),<br>    }<br>}</pre><p>The Success(body) and Error(code, msg) syntax is destructuring happening directly inside the match arm. You&#39;re not just routing to a branch but also you&#39;re pulling the data out of the variant at the same time, in the same line.</p><p>Compare this with the Kotlin equivalent:</p><pre>sealed class NetworkState {<br>    object Loading : NetworkState()<br>    data class Success(val body: String) : NetworkState()<br>    data class Error(val code: Int, val message: String) : NetworkState()<br>}<br><br>fun handleState(state: NetworkState) {<br>    when (state) {<br>        is NetworkState.Loading  -&gt; println(&quot;Loading...&quot;)<br>        is NetworkState.Success  -&gt; println(&quot;Response: ${state.body}&quot;)<br>        is NetworkState.Error    -&gt; println(&quot;Error ${state.code}: ${state.message}&quot;)<br>    }<br>}</pre><p>Same intent. But Kotlin needs two constructs (sealed class + data class) to do what Rust handles with one. And the Kotlin when above is only exhaustive because the compiler infers the expression context. Change it to a statement, add a new variant later, and the compiler might not stop you. The Rust version doesn&#39;t need that vigilance, the contract is enforced structurally.</p><p>For Android developers working with UiState&lt;T&gt;, the translation is direct:</p><pre>// Kotlin<br>sealed class UiState&lt;T&gt; {<br>    object Loading : UiState&lt;Nothing&gt;()<br>    data class Success&lt;T&gt;(val data: T) : UiState&lt;T&gt;()<br>    data class Error(val message: String) : UiState&lt;Nothing&gt;()<br>}<br><br>// Rust<br>enum UiState&lt;T&gt; {<br>    Loading,<br>    Success(T),<br>    Error(String),<br>}</pre><p>One enum. No sealed. No Nothing. Same semantics, less ceremony.</p><h3>Level 3: Option&lt;T&gt;, the Enum Behind Null Safety</h3><p>Option&lt;T&gt; is not a special language feature. It&#39;s a regular enum defined in the Rust standard library:</p><pre>// This is literally the definition in std<br>enum Option&lt;T&gt; {<br>    Some(T),<br>    None,<br>}</pre><p>That’s it. Two variants. Some(T) means the value exists and carries it. None means it doesn&#39;t. And because it&#39;s an enum, match applies:</p><pre>fn find_user(id: u32) -&gt; Option&lt;String&gt; {<br>    if id == 1 {<br>        Some(String::from(&quot;Taufik&quot;))<br>    } else {<br>        None<br>    }<br>}<br><br>fn main() {<br>    let result = find_user(1);<br>    match result {<br>        Some(name) =&gt; println!(&quot;Found: {}&quot;, name),<br>        None       =&gt; println!(&quot;User not found&quot;),<br>    }<br>}</pre><p>There is no path to name that bypasses the None case. The structure of the type prevents it.</p><p>Compare this with Kotlin’s nullable:</p><pre>fun findUser(id: Int): String? {<br>    return if (id == 1) &quot;Taufik&quot; else null<br>}<br><br>fun main() {<br>    val result = findUser(1)<br>    println(result!!)  // compiles, crashes if result is null<br>}</pre><p>The Kotlin version lets you skip the null check with !!. Rust has no equivalent because null doesn&#39;t exist. You&#39;re not only checking whether a value is null but also you&#39;re unpacking a container that either holds something or doesn&#39;t.</p><h3>When You Only Care About the Some Case</h3><p>Full match is explicit but sometimes more than you need. Rust gives you a shorthand:</p><pre>if let Some(name) = find_user(1) {<br>    println!(&quot;Found: {}&quot;, name);<br>}<br>// if it&#39;s None, nothing happens -- no else required</pre><p>This is the equivalent of Kotlin’s ?.let { }. You execute the body only if the value is present, and the None case is a silent no-op by design.</p><h3>When You Need A Default Value</h3><pre>let name = find_user(1).unwrap_or(String::from(&quot;Guest&quot;));</pre><p>This is the padanan of ?: &quot;Guest&quot; in Kotlin. If the Option is Some(value), you get the value. If it&#39;s None, you get the default. The name unwrap_or is intentional, it makes you conscious that you&#39;re unwrapping a container and providing a fallback for when it&#39;s empty. It&#39;s not syntactic sugar over null; it&#39;s explicit acknowledgment that the value might not be there.</p><p><strong>When you need to transform the value</strong></p><pre>let upper_name = find_user(1).map(|name| name.to_uppercase());<br>// upper_name is Option&lt;String&gt;, not String<br>// Some(&quot;TAUFIK&quot;) if found, None if not</pre><p>map() on an Option applies a function to the inner value if it&#39;s Some, and passes None through unchanged. No null check. No crash risk. The transformation is safe by construction.</p><p>For chaining operations that themselves return Option:</p><pre>let email = find_user(1).and_then(|name| find_email_by_name(name));<br>// if find_user returns None, find_email_by_name never runs<br>// if find_user returns Some(name), it passes name to find_email_by_name<br>// result is Option&lt;String&gt;, not Option&lt;Option&lt;String&gt;&gt;</pre><p>and_then flattens the result, no nested Option&lt;Option&lt;T&gt;&gt;. The chain short-circuits at the first None. This is equivalent to chaining ?. calls in Kotlin, but the type system makes the behavior explicit rather than inferring it from syntax.</p><h3>Impacts</h3><h3>Technical</h3><p>The exhaustive matching guarantee isn’t just ergonomic. It’s a structural property of the language.</p><p>The Rust compiler performs exhaustiveness checking at compile time: it analyzes every possible variant of the matched type and confirms that all of them are handled. If a new variant is added to an enum later, every match expression that doesn&#39;t cover it becomes a compile error automatically. No grep required. No test coverage needed to catch the regression.</p><p>This is documented in the Rust Reference under <a href="https://doc.rust-lang.org/reference/expressions/match-expr.html">Pattern Matching</a> and in The Rust Book’s chapter on <a href="https://doc.rust-lang.org/book/ch06-02-match.html">The match Control Flow Construct</a>.</p><p>Option&lt;T&gt; as a replacement for null has a direct technical implication: there is no null pointer to dereference. The entire category of null dereference errors, one of the most common sources of runtime crashes, is eliminated by the type system. The Rust Book covers this in <a href="https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum-and-its-advantages-over-null-values">The Option Enum and Its Advantages Over Null Values</a>.</p><p>For Android developers using Rust via the NDK, this has a practical implication: components written in Rust (audio processing, image decoding, cryptography, network parsing) cannot crash from null dereferences by construction. The Android Open Source Project documents Rust integration at <a href="https://source.android.com/docs/setup/build/rust/building-rust-modules/overview">source.android.com/docs/setup/build/rust</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZ4meTi6XR7qKJTefJ7YdQ.png" /></figure><h3>Business</h3><p>The null reference problem has a well-documented origin story. Tony Hoare, the computer scientist who invented null references in 1965, called it his <em>“billion-dollar mistake”</em> in a keynote at QCon London 2009. His estimate referred to the cumulative cost of null-related bugs and crashes across the software industry over decades. The full talk is archived at <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare</a>.</p><p>The cost pattern hasn’t improved much. The Consortium for Information and Software Quality estimated in their 2022 report that poor software quality cost the US alone $2.41 trillion, with runtime defects as a significant contributor. That report is available at <a href="https://www.it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report/">it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report</a>.</p><p>In 2019, Microsoft Research published findings showing that approximately 70% of the CVEs (Common Vulnerabilities and Exposures) they identified in their C and C++ codebases were caused by memory safety issues, a category that includes null dereferences. That post is at <a href="https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/">msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code</a>.</p><p>On the Android side specifically, Google published data showing that after adopting Rust in Android OS components starting in 2021, the share of memory safety vulnerabilities in newly written code dropped from 76% to 35% over two years. That finding is documented in the Google Security Blog: <a href="https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html">security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html</a>.</p><p>For teams building Android apps with Rust components (NDK, audio, media, cryptography), this translates directly to fewer hotfixes, fewer Play Store emergency releases, and fewer crash reports that trace back to a mishandled state that should have been caught at compile time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNGPUNMoyXNtpAIUwzXdrQ.png" /></figure><h3>Wrapping Up</h3><p>Ownership answers: who owns this data. Borrowing answers: who’s allowed to use it. Lifetime answers: how long is that borrow valid. Generics answers: this logic works for any type, as long as it meets the contract.</p><p>Enum answers something different: what shape can this value actually take, and have you handled all of them?</p><p>Rust’s answer to that question is not a runtime check. It’s not a lint warning. It’s a compile-time guarantee. Every match is verified. Every variant is accounted for. And Option&lt;T&gt;, the enum that replaced null, ensures that &quot;this value might not exist&quot; is never hidden behind a type that looks like it always does.</p><p>The system is consistent. Every piece connects. And the payoff starts showing up the moment you ship code that used to crash in Kotlin and no longer can in Rust.</p><p>In the next article, we’ll look at <strong>Error Handling with </strong><strong>Result&lt;T, E&gt;</strong> and why Rust&#39;s version is nothing like the try-catch you&#39;ve been using in Kotlin. Exceptions are invisible in function signatures. Result is not. There&#39;s a lot more going on under the hood than you might expect.</p><h3>References</h3><ol><li>The Rust Reference: <a href="https://doc.rust-lang.org/reference/expressions/match-expr.html">Pattern Matching</a></li><li>The Rust Book: <a href="https://doc.rust-lang.org/book/ch06-02-match.html">The match Control Flow Construct</a></li><li>The Rust Book: <a href="https://www.notion.so/You-ve-Been-Using-Enums-Wrong-Your-Whole-Career-Rust-Is-Here-to-Prove-It-37a882e395f48022902bc11309d3c72c?pvs=21">The Option Enum and Its Advantages Over Null Values</a></li><li>Android Open Source Project: <a href="https://source.android.com/docs/setup/build/rust/building-rust-modules/overview">Rust in Android</a></li><li>Tony Hoare, “Null References: The Billion Dollar Mistake,” QCon London 2009 — <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/</a></li><li>CISQ, “The Cost of Poor Quality Software in the US: A 2022 Report” — <a href="https://www.it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report/">https://www.it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report/</a></li><li>Microsoft Security Response Center, “A proactive approach to more secure code,” 2019 — <a href="https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/">https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/</a></li><li>Google Security Blog, “Memory Safe Languages in Android 13,” 2022 — <a href="https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html">https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa8dbb3b746" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/youve-been-using-enums-wrong-your-whole-career-rust-is-here-to-prove-it-4fa8dbb3b746">You’ve Been Using Enums Wrong Your Whole Career. Rust Is Here to Prove It.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When Rust Compiles Your Generic Code? The Answer Changes Everything]]></title>
            <link>https://blog.stackademic.com/what-happens-when-rust-compiles-your-generic-code-the-answer-changes-everything-6be8d473a37e?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/6be8d473a37e</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 07:18:27 GMT</pubDate>
            <atom:updated>2026-06-09T00:57:34.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYummWVfJJa_ctYHDTvwUQ.png" /><figcaption>Kotlin vs Rust Generics</figcaption></figure><p>You’ve probably written something like this in Kotlin before:</p><pre>fun formatCurrency(amount: Int): String = &quot;Rp${amount}&quot;<br>fun formatCurrency(amount: Long): String = &quot;Rp${amount}&quot;<br>fun formatCurrency(amount: Double): String = &quot;Rp${amount}&quot;</pre><p>Three functions, same logic, different types, and when a new requirement comes in, let’s say Float support, you write a fourth. The logic never changes but only the type does.</p><p>That’s the exact problem Generics was built to solve.</p><p>But in Rust, Generics is more than a convenience. It’s central to how the language delivers on one of its core promises: <strong>zero-cost abstractions</strong>. You write flexible, reusable code, and the runtime pays nothing extra for it.</p><p>If ownership answers <em>“who owns the data?”</em>, borrowing answers <em>“who’s allowed to use it?”</em>, and lifetime answers <em>“how long is that valid?”</em>, then Generics answers a different question:</p><blockquote><strong>Why write the same logic twice when one version can handle all types?</strong></blockquote><h3>The Problem It Was Built to Solve</h3><p>Think about how you’d model a loading state in a typical Android project:</p><pre>// Without Generics<br>sealed class UiStateInt {<br>    object Loading : UiStateInt()<br>    data class Success(val data: Int) : UiStateInt()<br>    data class Error(val message: String) : UiStateInt()<br>}<br><br>sealed class UiStateString {<br>    object Loading : UiStateString()<br>    data class Success(val data: String) : UiStateString()<br>    data class Error(val message: String) : UiStateString()<br>}</pre><p>Same structure. Different types. Every change you make to one, you have to remember to make to the other. With Generics, this collapses into a single definition:</p><pre>// With Generics<br>sealed class UiState&lt;T&gt; {<br>    object Loading : UiState&lt;Nothing&gt;()<br>    data class Success&lt;T&gt;(val data: T) : UiState&lt;T&gt;()<br>    data class Error(val message: String) : UiState&lt;Nothing&gt;()<br>}</pre><p>Rust handles this the same way. The Rust Reference puts it simply: <em>“Generics are a facility for writing code in terms of types which will later be supplied by the user of the generic code.”</em> (<a href="https://doc.rust-lang.org/reference/items/generics.html">The Rust Reference</a>)</p><p>You write the logic once. The caller decides the type.</p><h3>Generics at a Glance</h3><p>Generics is a way to write code that works across multiple types without duplicating it. The type is treated as a parameter, usually written as &lt;T&gt;, short for “Type” by convention.</p><pre>fn largest&lt;T&gt;(list: &amp;[T]) -&gt; &amp;T {<br>    let mut largest = &amp;list[0];<br>    for item in list {<br>        if item &gt; largest {<br>            largest = item;<br>        }<br>    }<br>    largest<br>}</pre><p>The &lt;T&gt; after the function name is what makes this generic. Any type can come in: integers, strings, custom structs, as long as it satisfies whatever constraints the function needs (more on that in the implementation section).</p><p>Generics appears in four places in Rust:</p><pre>// 1. Function<br>fn first&lt;T&gt;(list: &amp;[T]) -&gt; &amp;T { &amp;list[0] }<br><br>// 2. Struct<br>struct Wrapper&lt;T&gt; {<br>    value: T,<br>}<br><br>// 3. Enum<br>enum Option&lt;T&gt; {<br>    Some(T),<br>    None,<br>}<br><br>// 4. impl block<br>impl&lt;T&gt; Wrapper&lt;T&gt; {<br>    fn get(&amp;self) -&gt; &amp;T {<br>        &amp;self.value<br>    }<br>}</pre><p>Option&lt;T&gt; is one you&#39;ll use constantly in Rust. It&#39;s a generic enum from the standard library where T is whatever type you&#39;re wrapping inside it.</p><h3>Not Just for Library Authors</h3><p>In Kotlin, Generics can feel optional at first. You can write entire features without touching &lt;T&gt; explicitly. But the moment you start building reusable components like a base ViewModel, a network response wrapper, or a repository abstraction, it becomes unavoidable.</p><p>Rust is similar, but a few groups run into it earlier:</p><ul><li><strong>Application developers</strong> encounter Generics the moment they touch Option&lt;T&gt;, Result&lt;T, E&gt;, Vec&lt;T&gt;, or HashMap&lt;K, V&gt;. These are all generic types from the standard library. If you&#39;ve used any of them, you&#39;ve already been using Generics.</li><li><strong>Library and utility authors</strong> hit it almost immediately. Writing a function or data structure meant to work across types requires explicit type parameters.</li><li><strong>Android engineers working with the NDK</strong>, building shared libraries or cross-platform Rust code, encounter Generics when defining shared data models across the FFI boundary.</li><li><strong>Anyone reading Rust compiler errors</strong> will find that understanding Generics turns cryptic trait-bound error messages into something actually actionable.</li></ul><p>The short version: every time you write Vec&lt;String&gt; or Option&lt;i32&gt;, you&#39;re already using Generics. Understanding why it works the way it does makes you far more confident when things don&#39;t compile.</p><h3>Three Signals You Need Generics</h3><p>There are three moments where reaching for Generics is the right call.</p><ul><li>The first is when you’re writing the same function for different types. That’s exactly the formatCurrency situation from the opening. Same logic, different input type, no reason to duplicate it.</li><li>The second is when you’re building a container or wrapper that should work regardless of what’s inside it. An API response wrapper, a pagination model, a cache entry: these are type-agnostic by nature.</li><li>The third is whenever you’re already working with standard library types. Every Vec&lt;String&gt;, every Option&lt;i32&gt;, every Result&lt;User, AppError&gt; is a generic type in use. You&#39;re not learning something new here. You&#39;re finally seeing what was always there.</li></ul><h3>Generics in Practice: Functions, Structs, Enums, and impl Blocks</h3><p>Generics in Rust can appear in four places. Each one serves a slightly different purpose.</p><pre>// 1. Function — logic that works for any type T<br>fn first&lt;T&gt;(list: &amp;[T]) -&gt; &amp;T {<br>    &amp;list[0]<br>}<br><br>// 2. Struct — a container that holds any type T<br>struct Wrapper&lt;T&gt; {<br>    value: T,<br>}<br><br>// 3. Enum — a type that represents one of several possibilities<br>enum ApiState&lt;T&gt; {<br>    Loading,<br>    Success(T),<br>    Error(String),<br>}<br><br>// 4. impl block — methods for all T<br>impl&lt;T&gt; Wrapper&lt;T&gt; {<br>    fn get(&amp;self) -&gt; &amp;T {<br>        &amp;self.value<br>    }<br>}<br><br>// impl block — methods only for Wrapper&lt;i32&gt;<br>impl Wrapper&lt;i32&gt; {<br>    fn double(&amp;self) -&gt; i32 {<br>        self.value * 2<br>    }<br>}</pre><p>The last two impl blocks are worth noting. get() is available on any Wrapper&lt;T&gt;, but double() only exists when T is i32. Wrapper&lt;String&gt; won’t have it. That kind of precision, attaching behavior to a specific type instantiation, isn’t something Kotlin gives you without extra workarounds.</p><h3>How to Implement It</h3><p>Three levels, from most common to most nuanced.</p><h3>Level 1: Generic Function</h3><p>You have logic that should work across types. One function handles it all.</p><pre>fn largest&lt;T: PartialOrd&gt;(list: &amp;[T]) -&gt; &amp;T {<br>    // T: PartialOrd means T must support comparison (&gt;, &lt;)<br>    // Without this, the compiler can&#39;t guarantee &gt; is valid for T<br>    let mut largest = &amp;list[0];<br>    for item in list {<br>        if item &gt; largest {<br>            largest = item;<br>        }<br>    }<br>    largest<br>}<br><br>fn main() {<br>    let numbers = vec![10, 40, 25, 60, 5];<br>    let chars = vec![&#39;y&#39;, &#39;m&#39;, &#39;a&#39;, &#39;q&#39;];<br>    println!(&quot;{}&quot;, largest(&amp;numbers)); // 60<br>    println!(&quot;{}&quot;, largest(&amp;chars));   // y<br>}</pre><p>T: PartialOrd is a <strong>trait bound</strong>, the way you constrain which types T can be. This is Rust&#39;s equivalent of Comparable&lt;T&gt; in Kotlin. The function still accepts any type, but only types that can actually be compared.</p><h3>Level 2: Generic Struct and Method</h3><p>Think UiState&lt;T&gt; from your Android projects. Same pattern, but in Rust:</p><pre>struct ApiResponse&lt;T&gt; {<br>    data: T,<br>    status_code: u16,<br>    message: String,<br>}<br><br>impl&lt;T&gt; ApiResponse&lt;T&gt; {<br>    fn new(data: T, status_code: u16, message: String) -&gt; Self {<br>        ApiResponse { data, status_code, message }<br>    }<br>    fn is_success(&amp;self) -&gt; bool {<br>        self.status_code &gt;= 200 &amp;&amp; self.status_code &lt; 300<br>    }<br>    fn get_data(&amp;self) -&gt; &amp;T {<br>        &amp;self.data<br>    }<br>}<br><br>fn main() {<br>    let response_str = ApiResponse::new(<br>        String::from(&quot;User profile loaded&quot;),<br>        200,<br>        String::from(&quot;OK&quot;),<br>    );<br>    let response_num = ApiResponse::new(42_u32, 200, String::from(&quot;OK&quot;));<br>    println!(&quot;Success: {}&quot;, response_str.is_success()); // true<br>    println!(&quot;Data: {}&quot;, response_num.get_data());       // 42<br>}</pre><p>Same intent as data class ApiResponse&lt;T&gt; in Kotlin, but with compile-time ownership guarantees that don&#39;t need a GC to enforce.</p><h3>Level 3: Multiple Type Parameters</h3><p>Sometimes one type parameter isn’t enough. Result&lt;T, E&gt; is the most iconic example in Rust, generic over both the success type and the error type:</p><pre>enum AppResult&lt;T, E&gt; {<br>    Ok(T),<br>    Err(E),<br>}<br><br>fn parse_user_id(input: &amp;str) -&gt; AppResult&lt;u32, String&gt; {<br>    match input.trim().parse::&lt;u32&gt;() {<br>        Ok(id)  =&gt; AppResult::Ok(id),<br>        Err(_)  =&gt; AppResult::Err(format!(&quot;&#39;{}&#39; is not a valid user ID&quot;, input)),<br>    }<br>}<br><br>fn main() {<br>    match parse_user_id(&quot;42&quot;) {<br>        AppResult::Ok(id)  =&gt; println!(&quot;User ID: {}&quot;, id),<br>        AppResult::Err(e)  =&gt; println!(&quot;Error: {}&quot;, e),<br>    }<br>    match parse_user_id(&quot;abc&quot;) {<br>        AppResult::Ok(id)  =&gt; println!(&quot;User ID: {}&quot;, id),<br>        AppResult::Err(e)  =&gt; println!(&quot;Error: {}&quot;, e),<br>    }<br>}</pre><p>If you’ve worked with Kotlin’s sealed class with Success and Error variants, Result&lt;T, E&gt; will feel immediately natural. The key difference: the compiler forces you to handle both cases, every time.</p><h3>Impact</h3><h4>Technical</h4><p>The most important thing to understand about Rust Generics is how it’s implemented under the hood, because this is where it diverges significantly from other languages.</p><p>The Rust Book states it plainly: <em>“Rust implements generics in such a way that your code doesn’t run any slower using generic types than it would with concrete types.”</em> (<a href="https://doc.rust-lang.org/book/ch10-01-syntax.html">The Rust Programming Language</a>)</p><p>The mechanism is called <strong>monomorphization</strong>. At compile time, Rust takes your generic code and generates a separate, fully concrete version for each type that uses it. You write one function, and the compiler produces as many concrete versions as needed.</p><pre>// You write:<br>fn largest&lt;T: PartialOrd&gt;(list: &amp;[T]) -&gt; &amp;T { ... }<br><br>// Rust compiles into:<br>fn largest_i32(list: &amp;[i32]) -&gt; &amp;i32 { ... }<br>fn largest_f64(list: &amp;[f64]) -&gt; &amp;f64 { ... }</pre><p>Each compiled version is fully optimized for its type with no runtime dispatch and no overhead. The numbers from independent benchmarks back this up. According to the Computer Language Benchmarks Game, Rust outperforms Go by 2x to 12x across CPU-bound tasks, with the widest gap appearing in memory-intensive workloads. (<a href="https://tech-insider.org/rust-vs-go-2026-2/">Rust vs Go 2026, tech-insider.org</a>) Go’s generic implementation, by contrast, uses partial monomorphization through a technique called GCShape stenciling, which means pointer types share a single compiled version and lose type-specific optimization. (<a href="https://www.infoq.com/news/2022/04/go-generics-performance/">InfoQ, 2022</a>)</p><p>On the JVM side, Kotlin uses <strong>type erasure</strong>: generic type information is stripped away at the bytecode level. This is why Kotlin needs reified inline functions whenever you need to access the actual type at runtime. In Rust, the type is always concrete after compilation. No workaround needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7N5FlRPdqAsahdTS2rbvjQ.png" /></figure><h4>Business</h4><p>The business case for compile-time type safety isn’t abstract. The Consortium for Information and Software Quality (CISQ) estimated that poor software quality cost the US alone $2.41 trillion in 2022, driven by vulnerabilities, technical debt, and defects that slipped through into production. (<a href="https://www.stocktitan.net/news/SNPS/software-quality-issues-in-the-u-s-cost-an-estimated-2-41-trillion-h7jy9ya6ijik.html">CISQ via Synopsys, 2022</a>)</p><p>The cost pattern is well established. Fixing a bug in production costs roughly 100x more than catching it at design time. (<a href="https://cloudqa.io/how-much-do-software-bugs-cost-2025-report/">IBM Systems Sciences Institute, via cloudqa.io</a>) And according to the State of DevOps Report, development teams spend 30 to 50% of their time fixing bugs and handling unplanned rework instead of shipping new features.</p><p>Generic abstractions don’t eliminate bugs entirely, but they do shrink the surface area for a specific and common class of them: type-related errors that only surface at runtime. Every duplicated function is a future fix that has to happen in multiple places. Every type-specific copy of the same logic is a test written twice, a PR that’s harder to review, and another place where inconsistencies quietly accumulate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKG2g8KHMhiPihn0agmVRg.png" /></figure><p>For teams adopting Rust in performance-critical Android components like audio pipelines, image processing, cryptography, or networking layers via the NDK, zero-cost Generics means the abstraction layer you need for clean, reusable code doesn’t come at the expense of the performance you need in production.</p><h3>Wrapping Up</h3><p>Generics isn’t really about writing less code. It’s about writing the right code once, and letting the compiler guarantee it works correctly across every type it’ll ever see.</p><p>Ownership says: <em>“who owns this data.”</em> Borrowing says: <em>“who’s allowed to use it.”</em> Lifetime says: <em>“how long that borrow is valid.”</em> Generics adds the final layer: <em>“this logic works for any type, as long as that type meets the contract.”</em></p><p>Together, these four concepts form a system where correctness is verified before the program ever runs. No runtime surprises. No defensive null-checks. No WeakReference that silently goes stale.</p><p>In the next article, we’ll look at <strong>Enum, Match and Option</strong>; and why Rust’s version is nothing like the constants you’ve been using in Kotlin. There’s a lot more going on under the hood than you might expect.</p><h3>References</h3><ol><li>The Rust Programming Language: <a href="https://doc.rust-lang.org/book/ch10-01-syntax.html">Generic Data Types</a></li><li>The Rust Reference: <a href="https://doc.rust-lang.org/reference/items/generics.html">Generics</a></li><li>The Rust Programming Language: <a href="https://doc.rust-lang.org/book/ch10-02-traits.html">Traits: Defining Shared Behavior</a></li><li>Rust by Example: <a href="https://doc.rust-lang.org/rust-by-example/generics.html">Generics</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6be8d473a37e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-happens-when-rust-compiles-your-generic-code-the-answer-changes-everything-6be8d473a37e">What Happens When Rust Compiles Your Generic Code? The Answer Changes Everything</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From WeakReference to Lifetime: How Rust Solves Memory Safety at Compile Time]]></title>
            <link>https://blog.stackademic.com/from-weakreference-to-lifetime-how-rust-solves-memory-safety-at-compile-time-8bb5fa4e431a?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb5fa4e431a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Mon, 18 May 2026 04:46:56 GMT</pubDate>
            <atom:updated>2026-05-18T08:47:23.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiNhA601Rj8vThHAiYyVQw.png" /><figcaption>Rust’s Lifetime</figcaption></figure><p>You’ve probably dealt with this in Android before:</p><p>Holding a reference to an Activity, but the Activity can be destroyed at any time due to rotation, back press, or low memory. The problem is, if that reference is still alive after the Activity dies, you get a memory leak. Or worse, you access the data and the app crashes.</p><p>The classic solution? WeakReference. But this is a defensive fix because the problem doesn&#39;t go away, it&#39;s just managed manually at runtime. You can still forget the null-check. You can still get the timing wrong.</p><p>The same problem shows up outside Android too. In high-throughput backend systems, game engines, and embedded systems, a reference that outlives its data is one of the hardest bugs to catch because it doesn’t always crash immediately. Sometimes it’s silent corruption. Sometimes data goes bad with no error message at all.</p><p>In Rust, this problem isn’t managed. It’s <strong>prevented</strong>.</p><p>Rust has a concept called <strong>Lifetime</strong>. Its job is to ensure a reference never outlives the data it points to. Not caught by an external tool. Not checked at runtime. But <strong>rejected outright by the compiler</strong> before your code can even run.</p><p>If ownership from <a href="https://medium.com/stackademic/from-kotlin-to-rust-4-mental-models-that-will-change-how-you-think-about-memory-2b2e62c542fc">Part 1</a> answers <em>“who owns the data?”</em>, and borrowing answers <em>“who’s allowed to borrow it?”</em>, then lifetime answers the final question that completes the picture:</p><blockquote><strong><em>How long is that borrow valid?</em></strong></blockquote><p>This article is part of the “Learn Rust from an Android Engineer’s POV” series and this is the part that makes the entire ownership system finally click.</p><h3>What is Lifetime?</h3><p>Lifetime is how the Rust compiler tracks how long a reference is valid and ensures that reference never outlives the data it points to.</p><p>This is not a runtime feature. There’s no overhead when the program runs. Lifetime is a pure compile-time check, meaning once your code compiles successfully, all of these guarantees are already in place.</p><p>Let’s look at a classic Android use case. You have a RecyclerView with an adapter that exposes a callback to a Fragment, say, a listener for when an item is tapped:</p><pre>class ItemAdapter(<br>    private val onItemClick: (Item) -&gt; Unit // callback to Fragment<br>) : RecyclerView.Adapter&lt;ItemAdapter.ViewHolder&gt;() {<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.itemView.setOnClickListener {<br>            onItemClick(items[position]) // invoke callback to Fragment<br>        }<br>    }<br>}</pre><p>In the Fragment:</p><pre>class ItemFragment : Fragment() {<br><br>    private lateinit var adapter: ItemAdapter<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        adapter = ItemAdapter(<br>            onItemClick = { item -&gt;<br>                // update UI in Fragment<br>                binding.titleText.text = item.name<br>            }<br>        )<br>        recyclerView.adapter = adapter<br>    }<br>}</pre><p>The problem surfaces when the Fragment is destroyed but the adapter isn’t. The onItemClick lambda implicitly holds a strong reference to the Fragment because it captures binding, which belongs to the Fragment. If the adapter is still alive in a memory pool or retained in a ViewModel while the Fragment is already gone, you get a memory leak or a crash when the lambda eventually gets invoked.</p><p>The defensive fix is WeakReference:</p><pre>class ItemAdapter(<br>    activity: FragmentActivity,<br>    onItemClick: (Item) -&gt; Unit<br>) : RecyclerView.Adapter&lt;ItemAdapter.ViewHolder&gt;() {<br><br>    private val fragmentRef = WeakReference(activity)<br>    private val clickListener = WeakReference(onItemClick)<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.itemView.setOnClickListener {<br>            if (fragmentRef.get() != null) {<br>                clickListener.get()?.invoke(items[position])<br>            }<br>        }<br>    }<br>}</pre><p>Safer, yes, but you still have to remember to null-check every time you use the callback. Forget it once, and the bug only shows up at runtime through a crash or a LeakCanary report.</p><p>In Rust, lifetime notation looks like this:</p><pre>fn longest&lt;&#39;a&gt;(x: &amp;&#39;a str, y: &amp;&#39;a str) -&gt; &amp;&#39;a str {<br>    if x.len() &gt; y.len() { x } else { y }<br>}</pre><p>&#39;a is a lifetime annotation. It means: <em>&quot;the return value is valid as long as both x and y are still valid.&quot;</em> The compiler uses this to guarantee no reference outlives its data, no null-check required.</p><h3>Why Does Lifetime Exist?</h3><p>Without lifetime, <strong>dangling references</strong> can happen.</p><p>A dangling reference is a reference that still exists, but the data it points to is already gone from memory. Think of a contact saved in your phone with a number that’s no longer active. The contact is still there, but calling it goes nowhere.</p><pre>fn get_greeting() -&gt; &amp;str {        // ❌ compiler error<br>    let greeting = String::from(&quot;Hello!&quot;);<br>    &amp;greeting                      // return memory address of greeting to caller<br>}                                  // function execution ends, exits its scope<br>                                   // greeting is dropped from memory<br>                                   // but caller already holds the address, now empty</pre><p>greeting is born inside get_greeting. The moment the function finishes executing and exits its scope, greeting is dropped from memory. But &amp;greeting was already handed to the caller. The caller is holding an address to memory that no longer has anything in it. That&#39;s a dangling reference.</p><p>Now compare that to a reference coming from outside:</p><pre>fn get_greeting(name: &amp;str) -&gt; &amp;str {  // ✅ safe<br>    name  // reference from the caller, the caller manages its lifetime<br>}</pre><p>Here, name doesn&#39;t belong to the function. It belongs to the caller. Its lifetime is controlled by the caller, not the function. No dangling.</p><p>The difference comes down to one thing: <strong>where the reference comes from.</strong></p><p>How do other languages handle this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2IXxHZO3uwlosYUa51_Lw.png" /></figure><p>You’re already familiar with the Java/Kotlin approach where the GC handles this behind the scenes. Rust has no GC. Lifetime is the replacement, but the work is done by the compiler, not the runtime.</p><h3>Who Should Understand Lifetime?</h3><p>Not every Rust developer needs to write lifetime annotations on a daily basis. The compiler handles most of it automatically through lifetime elision. But there are specific situations where understanding lifetime deeply becomes unavoidable.</p><ul><li>If you’re a <strong>library or utility author</strong>, you’ll run into lifetime annotations almost immediately. Writing functions that return references, or building structs that hold borrowed data, requires you to be explicit about how long that data is expected to live.</li><li>If you’re working in <strong>systems development</strong>, whether that’s embedded systems, game engines, or high-performance backends, lifetime is where Rust’s zero-overhead guarantee becomes most visible. This is the environment where lifetime shines the most.</li><li>If you’re an <strong>Android or mobile developer exploring Rust</strong>, especially for Android NDK or cross-platform use cases, understanding lifetime helps you reason about memory across language boundaries where the rules are strict and unforgiving.</li><li>And if you’ve ever stared at a <strong>Rust compiler error that mentions lifetime</strong>, you already know how cryptic it feels without a solid foundation. Understanding the concept is what turns those error messages from frustrating walls of text into clear, actionable guidance.</li></ul><p>The short version: if you’re writing everyday Rust applications, the compiler has your back. But the moment you start building abstractions, libraries, or structs that hold references, lifetime stops being optional.</p><h3>When Do You Need to Write Lifetime Annotations?</h3><p>This is what often makes people overthink it: <em>“does that mean I have to write </em><em>&#39;a every time I use a reference?&quot;</em></p><p>No. Most lifetimes are inferred automatically by the compiler through a feature called <em>lifetime elision</em>. For simple cases, you don’t need to write anything.</p><p>You only need explicit lifetime annotations in three situations:</p><p><strong>1. A function has multiple reference parameters and returns a reference</strong></p><pre>// ❌ Compiler confused: does the return value follow the lifetime of x or y?<br>fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str { ... }<br><br>// ✅ Explicit: return value follows whichever of x or y has the shorter lifetime<br>fn longest&lt;&#39;a&gt;(x: &amp;&#39;a str, y: &amp;&#39;a str) -&gt; &amp;&#39;a str { ... }</pre><p><strong>2. A struct holds a reference as a field</strong></p><pre>// ✅ This struct must not outlive the string it holds<br>struct Excerpt&lt;&#39;a&gt; {<br>    content: &amp;&#39;a str,<br>}</pre><p><strong>3. There’s ambiguity the compiler can’t resolve on its own</strong></p><p>If the compiler still complains after you write your code, the error message is usually clear enough to point exactly where the lifetime annotation needs to go.</p><h3>Where Does Lifetime Appear?</h3><p>Lifetime can appear in four places:</p><pre>// 1. Function signature<br>fn longest&lt;&#39;a&gt;(x: &amp;&#39;a str, y: &amp;&#39;a str) -&gt; &amp;&#39;a str { ... }<br><br>// 2. Struct definition<br>struct Config&lt;&#39;a&gt; {<br>    host: &amp;&#39;a str,<br>}<br><br>// 3. impl block<br>impl&lt;&#39;a&gt; Config&lt;&#39;a&gt; {<br>    fn get_host(&amp;self) -&gt; &amp;str {<br>        self.host<br>    }<br>}<br><br>// 4. &#39;static — a reference that lives for the entire program<br>let s: &amp;&#39;static str = &quot;Hello!&quot;;</pre><p>&#39;static is a special lifetime worth remembering. String literals like &quot;Hello!&quot; are always &#39;static because they&#39;re embedded directly into the program binary and remain valid for as long as the program runs.</p><h3>Implementation</h3><p>Three levels of lifetime usage, starting from the most common:</p><p><strong>Level 1: A function that returns one of two references</strong></p><pre>fn longest&lt;&#39;a&gt;(x: &amp;&#39;a str, y: &amp;&#39;a str) -&gt; &amp;&#39;a str {<br>    // &#39;a means: return value is valid as long as both x and y are valid<br>    // compiler picks the shorter lifetime between the two<br>    if x.len() &gt; y.len() { x } else { y }<br>}<br><br>fn main() {<br>    let s1 = String::from(&quot;longer&quot;);<br>    let result;<br>    {<br>        let s2 = String::from(&quot;xy&quot;);<br>        result = longest(s1.as_str(), s2.as_str());<br>        println!(&quot;{}&quot;, result); // ✅ valid, s1 and s2 are still alive<br>    }<br>    // println!(&quot;{}&quot;, result); // ❌ s2 is already gone outside this scope<br>}</pre><p><strong>Level 2: A struct that holds a reference</strong></p><pre>struct Excerpt&lt;&#39;a&gt; {<br>    content: &amp;&#39;a str, // this struct must not outlive the original string<br>}<br><br>fn main() {<br>    let article = String::from(&quot;One day in Jakarta...&quot;);<br><br>    let excerpt = Excerpt {<br>        content: &amp;article, // excerpt&#39;s lifetime is tied to article<br>    };<br><br>    println!(&quot;{}&quot;, excerpt.content); // ✅ article is still alive<br>} // article is dropped here, excerpt is already done too</pre><p><strong>Level 3: </strong><strong>&#39;static lifetime</strong></p><pre>// String literals are always valid for the entire program<br>let greeting: &amp;&#39;static str = &quot;Hello!&quot;;<br><br>// Useful for error messages or constant values<br>fn get_error_message(code: u32) -&gt; &amp;&#39;static str {<br>    match code {<br>        404 =&gt; &quot;Not found&quot;,<br>        500 =&gt; &quot;Internal server error&quot;,<br>        _   =&gt; &quot;Unknown error&quot;,<br>    }<br>}</pre><h3>Impact</h3><p>Before getting into the impact, it helps to know when lifetime is actually worth understanding deeply and what to watch out for when using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHURLVl4VEaziFtkwBpXpg.png" /></figure><h4>Technical</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjE9bWixA8p9HAdwi_4akA.png" /></figure><h4>Business</h4><p>Microsoft Security Response Center reported that around 70% of CVEs assigned to Microsoft each year are memory safety issues, and this has been consistent since 2006 (<a href="https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/">MSRC Blog, 2019</a>). And more relevant for us as Android engineers, Google estimates that 90% of Android vulnerabilities are memory safety issues (<a href="https://www.memorysafety.org/docs/memory-safety/">memorysafety.org</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3cgRcXHMPhdfGcbjhIN-Q.png" /></figure><h3>Wrapping Up</h3><p>Lifetime isn’t something you write every day. Most of the time, the compiler handles it on its own through lifetime elision.</p><p>But understanding the concept matters because lifetime is the final piece of the puzzle that makes Rust’s ownership system truly complete.</p><p>Ownership says: <em>“who owns this data.”</em> Borrowing says: <em>“who’s allowed to borrow it.”</em> Lifetime says: <em>“how long that borrow is valid.”</em></p><p>These three concepts work together, and the result is a system that delivers memory safety guarantees with no garbage collector, no runtime overhead, and no WeakReference that can go null at any moment.</p><p>In the next article, we’ll get into <strong>Generics — One Function for All Types</strong>, and why Rust’s approach here is more powerful than the Generics you already know from Kotlin.</p><h3>References</h3><ol><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html">Validating References with Lifetimes</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">References and Borrowing</a></li><li>Microsoft Security Response Center — <a href="https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/">A proactive approach to more secure code</a></li><li>Prossimo — <a href="https://www.memorysafety.org/docs/memory-safety/">Memory Safety</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb5fa4e431a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/from-weakreference-to-lifetime-how-rust-solves-memory-safety-at-compile-time-8bb5fa4e431a">From WeakReference to Lifetime: How Rust Solves Memory Safety at Compile Time</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struct, Traits, & Impl: How Rust Models the World Without Classes]]></title>
            <link>https://blog.stackademic.com/struct-traits-impl-how-rust-models-the-world-without-classes-543a5372c16d?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/543a5372c16d</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[traits]]></category>
            <category><![CDATA[impl]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Thu, 07 May 2026 03:00:55 GMT</pubDate>
            <atom:updated>2026-05-18T04:43:07.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2ptiADJVmPKpYUeS1HSVA.png" /><figcaption>Kotlin Data Class vs Struct, Traits, and Impl</figcaption></figure><p>In the <a href="https://medium.com/stackademic/string-vs-str-why-rust-has-two-string-types-and-what-it-says-about-memory-b95d59fcb1fe?source=user_profile_page---------1-------------b1b71b5dd036----------------------">previous part</a>, we figured out why Rust has two String types. We understood Stack vs. Heap. We understood that every byte must have a clear owner.</p><p>Now the question changes.</p><p>If Rust has no Garbage Collector and every piece of data must be managed explicitly, then how do we <em>organize</em> that data? How do we build an entity that has a name, has fields, and has behavior?</p><p>In Kotlin, the answer is obvious: <strong>class</strong>.</p><p>In Rust, the answer is: <strong>Struct, Impl, and Traits</strong>.</p><h3>What Are Struct, Traits, and Impl?</h3><h3>Struct: Where Data Lives</h3><p>Struct is how Rust defines a custom data type. If you’ve written <strong>data class</strong> in Kotlin, the concept is the same. You group related fields into one named entity.</p><pre>struct User {<br>  username: String,<br>  email: String,<br>  age: u32,<br>}</pre><p>Unlike Kotlin’s <strong>data class</strong>, which can have methods directly, in Rust it can’t. Struct stores data only. Full stop.</p><p>Behavior goes somewhere else.</p><h3>Traits: A Contract of Capabilities</h3><p>A trait is a contract. You’re defining: “anyone who implements this trait must be able to do these things.”</p><p>If you’re coming from Kotlin, this feels very familiar. It works like an <strong>interface</strong>. And the way you “attach” that contract to a struct is just as recognizable: <strong>impl Trait for Struct</strong>.</p><pre>trait Describable {<br>  fn describe(&amp;self) -&gt; String;<br>}</pre><p>The syntax <strong>impl Trait for Struct</strong> is the <em>only</em> way in Rust to say “this type has this capability.” There’s no other path. There’s no inheritance you can leverage as a shortcut.</p><p>And just like Kotlin interfaces can have default method bodies, traits in Rust can too.</p><h3>Impl: Where Behavior Lives</h3><p>The <strong>impl</strong> block is where you define methods for a struct. If the struct is the “shape of the data”, then <strong>impl</strong> is “what can be done with that data.”</p><pre>impl User {<br>  // Associated function - called without an instance<br>  // Equivalent to companion object function in Kotlin<br>  fn new(username: String, email: String, age: u32) -&gt; Self {<br>    Self { username, email, age } <br>  }<br>  <br>  // Regular method - &amp;self means read-only, no mutation<br>  fn greet(&amp;self) {<br>    println!(&quot;Hi, I&#39;m {}!&quot;, self.username);<br>  }<br>}</pre><p>Data and behavior are separated explicitly. This isn’t an accident, it’s a deliberate design decision. We’ll cover why in the next section.</p><h3>Why Is Rust Designed This Way?</h3><p>This is the most important part. Not just “what exists”, but “why it exists.”</p><h4>Why Are Data and Behavior Separated?</h4><p>In Kotlin, everything goes in one <strong>class</strong> block. Methods, fields, and constructors, all together.</p><p>Rust forces you to separate them. Struct for data, <strong>impl</strong> for behavior.</p><p>Why?</p><p>Because <strong>one struct can have multiple</strong> <strong>impl</strong> <strong>blocks</strong>. You can put general methods in one block and trait-related methods in another. The code becomes more modular. And when you’re reading a struct, you know exactly you’re reading <em>data</em>, not behavior buried somewhere inside.</p><pre>// Block for general behavior<br>impl User {<br>  fn new(...) -&gt; Self { ... }<br>}<br><br>// Block specific to a trait<br>impl Describable for User {<br>  fn describe(&amp;self) -&gt; String { ... }<br>}</pre><p>This is also what allows you to implement a trait from an external library for your own type that something inheritance simply can’t do.</p><h4>Why Traits Instead of Inheritance?</h4><p>This is the most interesting part for anyone coming from an OOP background.</p><h4>Rust has no class inheritance. At all.</h4><p>No <strong>open class</strong>, no extends, no parent-child hierarchy, and this isn’t a limitation. It’s a conscious choice.</p><p>Inheritance has well-known problems in software design:</p><ul><li>Changes in the parent class can break children you didn’t expect — the <em>fragile base class problem</em>.</li><li>Deep hierarchies become hard to reason about.</li><li>You’re forced to inherit everything, even when you only need one method.</li></ul><p>Rust replaces all of that with <strong>composition via traits</strong>.</p><p>You don’t say “AdminUser is a subtype of User.” You say “AdminUser has the capabilities that <strong>Describable</strong> has, and also the capabilities that <strong>Auditable</strong> has.”</p><p>And the way you declare that? Always with <strong>impl Trait for Struct</strong> — explicit, one by one, with nothing hidden or implicitly inherited.</p><pre>impl Describable for AdminUser { ... }<br>impl Auditable for AdminUser { ... }</pre><p>If <strong>AdminUser</strong> doesn’t implement <strong>Describable</strong>, the compiler will complain immediately. Nothing “accidentally works” because of a parent class above it. Every capability must be declared consciously.</p><p>For those already familiar with Jetpack Compose, this mindset isn’t entirely new. Composable functions, not class hierarchy. Composition over inheritance. Rust just takes that philosophy further, and makes it <em>the only option</em> at the language level.</p><h3>When Do You Use Them?</h3><ul><li>Use <strong>Struct</strong> — whenever you need to represent an entity with multiple related fields. <strong>User</strong>, <strong>Config</strong>, <strong>ApiResponse</strong>, and <strong>Order</strong>. If you’d write <strong>data class</strong> in Kotlin, you write <strong>struct</strong> in Rust.</li><li>Use <strong>Impl</strong> — whenever your struct needs behavior. Constructor, getters, methods that operate on that data. No behavior exists without <strong>impl</strong>.</li><li>Use <strong>Traits</strong> — whenever you need abstraction. When you want a function to accept <em>multiple types</em>, as long as those types fulfill a certain contract. This is the foundation of polymorphism in Rust.</li></ul><h3>Where Do They Usually Appear?</h3><p>Open any serious Rust codebase, and you’ll find all three within the first five minutes:</p><ul><li><strong>Domain modeling</strong> — all business entities are represented as structs. User, Product, Transaction — all structs.</li><li><strong>Error handling</strong> — custom error types in Rust are almost always structs implementing <strong>std::fmt::Display</strong> and <strong>std::error::Error</strong>.</li><li><strong>Standard library</strong> — almost everything in Rust’s <strong>std</strong> is a trait. <strong>Iterator</strong>, <strong>Display</strong>, <strong>Debug</strong>, <strong>Clone</strong>, <strong>From</strong>, <strong>Into</strong> are all traits. If you implement <strong>Display</strong> for your struct, you can immediately use <strong>println!(“{}”, my_struct)</strong>. Rust knows how to handle it because the contract is fulfilled.</li><li><strong>Generic programming </strong>— traits are used as <em>bounds</em> when writing generic functions. “This function accepts any type, as long as it implements this trait.”</li></ul><h3>Implementation</h3><p>Let’s use a more complete, realistic example. Imagine you’re building a domain model for a feature in your Android app.</p><p><strong>Step 1: Define the struct</strong></p><pre>struct Product {<br>  name: String, // product name<br>  price: f64, // price<br>  in_stock: bool, // available or not<br>}</pre><p><strong>Step 2: Add behavior via impl</strong></p><pre>impl Product {<br>  // Constructor - equivalent to companion object in Kotlin<br>  fn new(name: &amp;str, price: f64) -&gt; Self {<br>    Self {<br>      name: name.to_string(), // &amp;str -&gt; owned String<br>      price,<br>      in_stock: true, // default: available<br>    }<br>  }<br><br>  // &amp;self - read-only method<br>  fn display_price(&amp;self) {<br>    println!(&quot;{}: ${:.2}&quot;, self.name, self.price);<br>  }<br> <br>  // &amp;mut self - method that can mutate data<br>  fn mark_out_of_stock(&amp;mut self) {<br>    self.in_stock = false;<br>  }<br>}</pre><p><strong>Step 3: Define a trait and implement it</strong></p><p>This is where <strong>impl Trait for Struct</strong> does its work. This isn’t a shortcut from inheritance, it’s an explicit declaration that <strong>Product</strong> fulfills the <strong>Discountable</strong> contract. If you remove this block, <strong>Product</strong> has no such capability at all. Nothing is inherited from anywhere.</p><pre>trait Discountable {<br>  fn apply_discount(&amp;self, percent: f64) -&gt; f64;<br><br>  // Default implementation - can be overridden<br>  fn is_on_sale(&amp;self) -&gt; bool {<br>    false<br>  }<br>}<br><br>// Explicit declaration: Product fulfills the Discountable contract<br>impl Discountable for Product {<br>  fn apply_discount(&amp;self, percent: f64) -&gt; f64 {<br>    self.price * (1.0 - percent / 100.0)<br>  }<br><br>  // Override default: on sale if price is below $50<br>  fn is_on_sale(&amp;self) -&gt; bool {<br>    self.price &lt; 50.0<br>  }<br>}</pre><p><strong>Step 4: Use it all together</strong></p><pre>fn main() {<br>  let mut headset = Product::new(&quot;Rust Edition Headset&quot;, 35.0);<br>  headset.display_price();<br>  // Output: Rust Edition Headset: $35.00<br>   <br>  let discounted = headset.apply_discount(10.0);<br>  println!(&quot;Discounted price: ${:.2}&quot;, discounted);<br>  // Output: Discounted price: $31.50<br>   <br>  println!(&quot;On sale? {}&quot;, headset.is_on_sale());<br>  // Output: On sale? true<br>   <br>  headset.mark_out_of_stock();<br>  println!(&quot;In stock? {}&quot;, headset.in_stock);<br>  // Output: In stock? false<br>}</pre><p>Notice one thing: <strong>mark_out_of_stock</strong> requires <strong>&amp;mut; self,</strong> meaning you need to declare <strong>headset</strong> as <strong>mut</strong>. This isn’t a bug, this is Rust forcing you to be honest: <em>“this variable will be mutated.”</em></p><h3>Wrapping Up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpTfoTC7HKx4f0lQVav2tA.png" /><figcaption>Rust Composition Model</figcaption></figure><p><strong>Struct, Impl, and Traits</strong> aren’t three features standing on their own. They’re three layers working together to replace the one thing Rust doesn’t have: <strong>class</strong>.</p><p>Struct holds data, Impl defines behavior, and Traits define contracts. Those contracts must be declared explicitly with <strong>impl Trait for Struct</strong>, one by one with nothing hidden.</p><p>Because in Rust, nothing “accidentally works.” Every capability must be owned consciously.</p><p>In the next part, we’ll tackle <strong>Lifetimes — </strong>Rust’s way of making sure references never outlive the data they point to. It’s one of the concepts that trips up almost everyone coming from a GC language, and we’ll break it down the same way: from the problem first.</p><p><strong>References</strong></p><ol><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch05-01-defining-structs.html">Defining and Instantiating Structs</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch05-03-method-syntax.html">Method Syntax</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch10-02-traits.html">Traits: Defining Shared Behavior</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=543a5372c16d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/struct-traits-impl-how-rust-models-the-world-without-classes-543a5372c16d">Struct, Traits, &amp; Impl: How Rust Models the World Without Classes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String vs &str: Why Rust Has Two String Types (And What It Says About Memory)]]></title>
            <link>https://blog.stackademic.com/string-vs-str-why-rust-has-two-string-types-and-what-it-says-about-memory-b95d59fcb1fe?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95d59fcb1fe</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 06:06:36 GMT</pubDate>
            <atom:updated>2026-05-18T04:43:44.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADotS9HQYHHFAwEJYHCwaA.png" /><figcaption>String vs Heap</figcaption></figure><p>When we first start learning Rust, we’ll hit this question almost immediately: why does Rust have both String and &amp;str? Aren&#39;t they the same thing? Aren&#39;t they both just... text?</p><p>If we’re coming from Kotlin, we already know how easy it is: val name = &quot;Taufik&quot; , it’s done. No drama, no choices. But in Rust, we&#39;re forced to pick. And that choice isn&#39;t about style. It&#39;s about <strong>where our data actually lives in memory</strong>.</p><h3>A Quick Flashback: Years of Being Spoiled</h3><p>In <a href="https://yumtaufikhidayat.medium.com/from-kotlin-to-rust-4-mental-models-that-will-change-how-you-think-about-memory-2b2e62c542fc">the previous article</a>, we talked about how Kotlin — and the JVM in general — spoils us with a Garbage Collector. We never had to think about <em>where</em> an object lives in memory. The GC handles it. It always has.</p><p>Rust doesn’t have a GC. And because of that, it needs a clear contract: <strong>every piece of data must have a fixed address, and every address comes with its own rules.</strong> We choose upfront, is this data fixed-size at compile time, or does it grow dynamically at runtime?</p><p>That’s what Stack and Heap are about. Let’s meet them properly.</p><h3>Stack: Fast, Predictable, No-Nonsense</h3><p>As Android Engineers, we already know the Stack but we just know it by different names. There’s the back stack in Navigation when switching between Activities. There’s the call stack we stare at when debugging. There’s the stack trace in Logcat every time there’s a crash. Same concept, different context.</p><p>Stack works on one simple rule: <strong>Last In, First Out (LIFO)</strong>. Because of that simplicity, allocation and deallocation are automatic and predictable — blazing fast.</p><p>But there’s one condition: <strong>the size of the data must be known at compile time</strong>.</p><pre>let number: i32 = 42;    // Stack — compiler knows i32 is always 4 bytes<br>let active: bool = true; // Stack — compiler knows bool is always 1 byte</pre><p>Because the size is guaranteed, the compiler can reserve the exact space needed ahead of time. And when the variable goes out of scope? It’s freed instantly — no GC, no overhead, no waiting.</p><h3>Heap: Flexible, Powerful, Needs Discipline</h3><p>Heap is the bigger, more dynamic part of memory. Anything that can grow at runtime, or whose size isn’t known until the program is actually running, lives here.</p><p>But flexibility has a cost. Allocating on the Heap is slower — the system has to search for a free chunk of the right size. More importantly: <strong>data on the Heap is not cleaned up automatically</strong>.</p><p>In Kotlin, the GC handles that cleanup. In Rust, it’s handled by the Ownership system — the compiler enforces the rules, and if we break them, our code simply won’t compile. Now we can start to see why Ownership matters: without clear rules, data on the Heap either leaks or gets freed twice.</p><pre>let name = String::from(&quot;Taufik&quot;); // Heap — can grow, can be modified</pre><h3>So What’s Actually Different Between &amp;str and String?</h3><p>Now the original question starts to answer itself. Both store text. But they live in different places, with very different characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oe0ECOh2Z9M26JsDitSGTQ.png" /></figure><pre>let s1 = &quot;Hello&quot;;               // &amp;str — Stack, fixed, immutable<br>let s2 = String::from(&quot;Hello&quot;); // String — Heap, dynamic, mutable</pre><p>&amp;str is a reference to text that already exists somewhere. Its size is fixed at compile time, so it sits comfortably on the Stack. String, on the other hand, owns its data, lives on the Heap, and can grow dynamically as needed.</p><h3>Visualization: How They Actually Live in Memory</h3><p>String on the Stack actually only stores three things: a pointer to the data on the Heap, the current length, and the maximum capacity. The actual text lives on the Heap. Meanwhile, &amp;str stores its data directly on the Stack because the size is already known from the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*So24Llas-eYOSPsEJoOMYg.png" /></figure><h3>When to Use Which?</h3><p>The rule of thumb is straightforward:</p><p><strong>Use </strong><strong>&amp;str</strong> — when the text is fixed, won&#39;t change, and is known upfront. App names, error labels, hardcoded constants.</p><pre>fn get_app_name() -&gt; &amp;&#39;static str {<br>    &quot;MyApp&quot; // lives for the entire duration of the program<br>}</pre><blockquote><em>&#39;static means this data lives as long as the program runs and is never removed from memory while the app is active.</em></blockquote><p><strong>Use </strong><strong>String</strong> — when the text is dynamic. User input, network responses, anything that needs to be built or modified at runtime.</p><pre>fn build_log_message(user_id: &amp;str, action: &amp;str) -&gt; String {<br>    format!(&quot;[LOG] User {} performed {}&quot;, user_id, action)<br>}</pre><h3>One Important Warning: clone() Is Expensive</h3><p>Before we understand why clone() is expensive, we need to understand why it exists.</p><p>In the <a href="https://medium.com/@yumtaufikhidayat/from-kotlin-to-rust-4-mental-models-that-will-change-how-you-think-about-memory-2b2e62c542fc">previous article</a>, we covered Rust’s <strong>Move</strong> rule: when data is moved to another variable, the original owner is immediately considered “dead.”</p><pre>let s1 = String::from(&quot;Hello&quot;);<br>let s2 = s1; // ownership moves to s2<br>println!(&quot;{}&quot;, s1); // ❌ ERROR — s1 is gone</pre><p>What if we genuinely need both variables to stay alive? That’s where clone() comes in.</p><pre>let s1 = String::from(&quot;Hello&quot;);<br>let s2 = s1.clone(); // s1 stays alive, s2 gets a full copy<br>println!(&quot;{}&quot;, s1); // ✅ still works<br>println!(&quot;{}&quot;, s2); // ✅ this works too</pre><p>clone() creates a <strong>complete duplicate</strong> of the data on the Heap , not just a pointer copy, but a full byte-for-byte copy into a new location.</p><p>And now that we understand Stack vs Heap, we can see why this matters. Every clone() call means Rust has to allocate new space on the Heap, copy all the bytes over, and create a new String on the Stack pointing to that copy.</p><p>For short strings, we won’t feel it. But imagine large sensor data, a full JSON response from an API, or an audio buffer being processed in real time — excessive clone() calls become a real performance tax, especially on low-end Android devices where memory is genuinely tight.</p><pre>let data = String::from(&quot;Very large sensor payload...&quot;);<br>let copy = data.clone(); // ⚠️ entire Heap data is duplicated</pre><p>That’s exactly why Rust nudges us toward <strong>Borrowing</strong> (&amp;) as the more efficient alternative — borrow the data, don&#39;t duplicate it.</p><h3>Wrapping Up</h3><p>Stack and Heap aren’t Rust-exclusive concepts. C and C++ have always required programmers to manage memory manually. What makes Rust different is that it <em>forces</em> us to think about where our data lives — but at the same time, <em>guarantees through the compiler</em> that we can’t make the fatal mistakes.</p><p>Now when someone asks why Rust has two string types, we have a complete answer: because &amp;str and String live in different places, with different responsibilities.</p><p>All four mental models from the first article — Ownership, Borrowing, Shadowing, and Slice — now have a stronger foundation. Because in the end, every single rule in Rust comes from one simple goal: <strong>ensure every byte in memory has a clear owner, without needing a GC to clean up the mess.</strong></p><p>In the next article, we’ll start exploring <strong>Struct, Impl, and Traits </strong>— and see how the complex data structures we build every day as Android Engineers can be modeled in Rust, without relying on Classes or Inheritance.</p><h3><strong>References</strong></h3><ol><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html">What is Ownership?</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/1.22.0/book/first-edition/the-stack-and-the-heap.html">The Stack and the Heap</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch15-01-box.html">Using Box&lt;T&gt; to Point to Data on the Heap</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95d59fcb1fe" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/string-vs-str-why-rust-has-two-string-types-and-what-it-says-about-memory-b95d59fcb1fe">String vs &amp;str: Why Rust Has Two String Types (And What It Says About Memory)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Kotlin to Rust: 4 Mental Models That Will Change How You Think About Memory]]></title>
            <link>https://blog.stackademic.com/from-kotlin-to-rust-4-mental-models-that-will-change-how-you-think-about-memory-2b2e62c542fc?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2e62c542fc</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 02:31:00 GMT</pubDate>
            <atom:updated>2026-05-18T04:43:55.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GTfFXAg21_7H-HZU.png" /><figcaption>From Kotlin to Rust</figcaption></figure><p>If you’ve spent years living inside the JVM/ART ecosystem as an Android Engineer, you’ve probably been “spoiled” by the Garbage Collector (GC). We rarely stress about an object’s lifecycle in memory, not really rarely but never 😁. As long as there’s no leaking static reference, the GC will clean it up.</p><p>But the moment you touch Rust code especially for NDK needs, high-performance engines, or shared logic, you’re forced back to basics. In Rust, memory is not a “later” problem. It’s a “right now” problem. Moving from Kotlin to Rust isn’t just about switching syntax. It’s about switching how you think. In Rust, memory is an asset, and every asset must have a clear owner.</p><p>Here are the 4 core mental models you need to internalize.</p><h3>1. Ownership &amp; Move: The Full Handover</h3><p>In Kotlin, writing val b = a gives you two references pointing to the same object on the Heap. But in Rust, that same operation is called a <strong>Move</strong> and every piece of data can only have one owner.</p><ul><li><strong>Logic</strong>: Ownership transfers completely. If a is given to b, then a is considered &quot;dead&quot; by the compiler.</li><li><strong>Impact</strong>: The variable a immediately becomes invalid and cannot be accessed after that line.</li><li><strong>Why</strong>: This is how Rust guarantees memory safety without a GC. There’s no scenario for a Double Free error because every byte in memory has exactly one owner responsible for cleaning it up when it goes out of scope.</li></ul><pre>fn main() {<br>    // String is stored on the Heap<br>    let s1 = String::from(&quot;Hello World&quot;);<br>    <br>    // Ownership of s1 is moved to s2<br>    let s2 = s1; <br><br>    // println!(&quot;{}&quot;, s1); <br>    // ^^^ ERROR: value borrowed here after move<br>    // s1 is now &quot;dead&quot; - its ownership has transferred to s2.<br>    <br>    println!(&quot;Data lives in s2: {}&quot;, s2);<br>}</pre><p>In Kotlin, s2 = s1 simply copies a reference. In Rust, it&#39;s a complete transfer of memory responsibility. No shared ownership, no ambiguity.</p><h3>2. Borrowing: A Compile-Time Read-Write Lock</h3><p>Ever hit a ConcurrentModificationException in Android? That happens because something tries to modify data while another part of the code is still reading it. Rust solves this problem entirely at compile time through <strong>Borrowing</strong> (&amp;).</p><ul><li><strong>Immutable (</strong><strong>&amp;)</strong>: You can have as many &quot;readers&quot; as you want, as long as nobody is writing.</li><li><strong>Mutable (</strong><strong>&amp;mut)</strong>: If one part of the code wants to write, it must be the only one doing anything with that data — no other readers or writers allowed.</li></ul><p>Think of it like a Read-Write Lock in a database, or a Mutex / ReadWriteLock that the compiler enforces automatically. If your code violates these rules, it simply won&#39;t compile. No runtime surprises, no race conditions slipping into production.</p><pre>fn main() {<br>    let mut status = String::from(&quot;Pending&quot;);<br><br>    // Immutable borrow: Multiple readers are fine<br>    let r1 = &amp;status;<br>    let r2 = &amp;status;<br>    println!(&quot;Current status: {} and {}&quot;, r1, r2);<br>    // Mutable borrow: Must be the sole writer<br>    let r3 = &amp;mut status;<br>    r3.push_str(&quot; - Processed&quot;);<br>    <br>    // println!(&quot;{}&quot;, r1); // ERROR: Can&#39;t read while someone is writing (r3)<br>    <br>    println!(&quot;Updated status: {}&quot;, r3);<br>}</pre><p>This is essentially a <strong>Compile-time Mutex</strong>. You will never be able to modify data that another function is currently reading. The compiler catches it before your users ever do.</p><h3>3. Shadowing: Data Transformation Without Namespace Pollution</h3><p>If you’ve written a lot of Java or Kotlin, you’ve probably fallen into this habit: creating intermediate variables like ageString, ageInt, ageValidated just to track a single value through its transformations. Rust offers a cleaner solution called <strong>Shadowing</strong>.</p><ul><li><strong>Pattern</strong>: Re-declare a variable with the same name using the let keyword.</li><li><strong>Use Case</strong>: Perfect for data cleaning or type conversion (e.g., from a String input to an i32) without inventing new variable names that add noise.</li><li><strong>Warning</strong>: Use shadowing only for linear, nearby transformations. Avoid it in long functions because it can make it hard to trace where a value originally came from.</li></ul><pre>fn main() {<br>    let amount = &quot;50000&quot;; // String from user input<br><br>    // Shadowing for type conversion (String -&gt; i32)<br>    let amount: i32 = amount.parse().expect(&quot;Not a number&quot;);<br>    // Shadowing for business logic (e.g., add a transaction fee)<br>    let amount = amount + 2500;<br>    println!(&quot;Total transaction: Rp{}&quot;, amount);<br>}</pre><p>The previous variable is effectively “buried” by the new declaration. Your namespace stays clean, and your intent stays clear.</p><h3>4. Slice: Zero-Copy Data Views</h3><p>A <strong>Slice</strong> is a reference to a portion of a collection — like a String or an array. For performance-sensitive work, slices (&amp;str, &amp;[T]) are one of Rust&#39;s most powerful tools.</p><ul><li><strong>Syntax</strong>: &amp;data[start..end]</li><li><strong>Efficiency</strong>: A slice is just a “window” (pointer + length) into the original data. When you slice a String, Rust doesn&#39;t copy anything in RAM. It just points to the existing bytes.</li><li><strong>Types</strong>: &amp;str for text slices, &amp;[i32] for numeric array slices.</li></ul><p>In Android terms: imagine processing massive system logs or sensor data streams. Using slices means you manipulate data instantly, with zero additional memory allocation. This is especially critical when dealing with low-end devices where every kilobyte matters.</p><pre>fn main() {<br>    let log_entry = String::from(&quot;2026-04-12 ERROR: Connection timeout&quot;);<br><br>    // Slice: A window (pointer + length) - no data duplication in RAM<br>    let date = &amp;log_entry[0..10];    // &quot;2026-04-12&quot;<br>    let level = &amp;log_entry[11..16];  // &quot;ERROR&quot;<br>    println!(&quot;Log Date: {}, Severity: {}&quot;, date, level);<br>}</pre><p>Zero-copy by default is one of the core reasons Rust can match and sometimes exceed C++ in performance. No hidden allocations, no surprises.</p><h3>Feature Comparison: Kotlin vs Rust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZxxlTst9iqJoeAEBt_Kpg.png" /></figure><h3>Paradigm Comparison: Kotlin vs Rust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FevzXPnBW12lFHnVtsSWCA.png" /></figure><h3>Why Does Rust Feel So “Strict”?</h3><p>Learning Rust at first, feels like arguing with a very pedantic Senior Engineer during code review, one who flags every single thing. But every “red underline” from the Borrow Checker is a production bug that never reaches your users.</p><p>For engineers used to handling complex systems or large-scale applications, Rust’s predictable type safety and memory management give you a level of precision that’s hard to match. You eliminate unnecessary runtime allocations which is critical on low-end Android devices where Out of Memory (OOM) crashes are a real concern.</p><p>With Rust, high performance isn’t just a feature. It’s a first-class architectural guarantee.</p><p>All four mental models: <strong>Ownership, Borrowing, Shadowing, and Slice</strong>, share the same foundation: a clear understanding of <em>where data actually lives in memory</em>.</p><p>In the next article, we’ll break down the difference between the <strong>Stack and the Heap</strong>, and why truly understanding this is the key to finally “clicking” with how Rust thinks.</p><h3>Reference</h3><ol><li><strong>Ownership and Move:</strong> <a href="https://doc.rust-lang.org/rust-by-example/scope/move.html">https://doc.rust-lang.org/rust-by-example/scope/move.html</a></li><li><strong>References and Borrowing:</strong> <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html</a></li><li><strong>Scope and Shadowing:</strong> <a href="https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html">https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html</a></li><li><strong>The Slice Type:</strong> <a href="https://doc.rust-lang.org/book/ch04-03-slices.html">https://doc.rust-lang.org/book/ch04-03-slices.html</a></li></ol><p><em>Follow me on </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> and </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> for more Android and Software Engineering content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2e62c542fc" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/from-kotlin-to-rust-4-mental-models-that-will-change-how-you-think-about-memory-2b2e62c542fc">From Kotlin to Rust: 4 Mental Models That Will Change How You Think About Memory</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String vs &str: Kenapa Rust Punya Dua Tipe String? Memahami Stack dan Heap]]></title>
            <link>https://yumtaufikhidayat.medium.com/string-vs-str-kenapa-rust-punya-dua-tipe-string-memahami-stack-dan-heap-b1c9284b5b5c?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c9284b5b5c</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 01:43:47 GMT</pubDate>
            <atom:updated>2026-04-29T03:18:22.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIJZPq520uchBoWP79kHSQ.png" /><figcaption>Stack vs heap</figcaption></figure><p>Saat pertama kali belajar Rust, hampir semua Android Engineer pasti punya pertanyaan yang sama: kenapa ada String dan &amp;str? Bukannya sama aja ya? Bukannya keduanya sama-sama teks ya? Bukannya sama-sama bisa menampung tipe data untuk teks ya? Dan segala macam pertanyaan yang senada dengan itu.</p><p>Kalau di Kotlin, kita sudah terbiasa dengan menulis val nama = &quot;Taufik&quot; dan selesai. Sudah cukup, tidak ada drama, dan tidak ada pilihan. Tapi di Rust itu semua berbeda. Kita dipaksa memilih dan pilihan itu bukan soal selera tapi soal <strong>di mana data itu hidup di memori</strong>.</p><h3>Kilas Balik: Dimanjakan Sejak Lama</h3><p>Di <a href="https://yumtaufikhidayat.medium.com/goodbye-garbage-collector-4-mental-model-rust-yang-wajib-dipahami-seorang-android-engineer-22b4250747b6">artikel sebelumnya</a>, kita sudah membahas bahwa Kotlin memanjakan kita dengan Garbage Collector (GC). Kita tidak pernah benar-benar peduli sebuah objek ada di mana di memori karena GC yang mengurus semuanya.</p><p>Di Rust, tidak ada GC. Dan karena tidak ada GC, Rust harus punya aturan yang jelas: <strong>setiap data harus punya tempat yang pasti dan setiap tempat punya konsekuensinya masing-masing.</strong> Jadi, kita bisa memilih apakah data disimpan dengan ukuran yang sudah pasti sejak compile time atau bersifat dinamis yang ukurannya baru diketahui saat runtime.</p><p>Kenalan yuk dengan <strong>Stack</strong> dan <strong>Heap</strong> di Rust.</p><h3>Stack: Si Cepat yang Teratur</h3><p>Sebagai Android Engineer, kita sebenarnya sudah sangat familiar dengan konsep Stack, hanya saja kita mengenalnya dalam beberapa wujud berbeda. Ada back stack di Navigation saat berpindah antar Activity atau Fragment, ada call stack yang muncul saat debugging, dan ada stack trace di Logcat setiap kali ada crash. Semuanya berbagi prinsip yang sama.</p><p>Cara kerja Stack cukup sederhana yaitu dengan <strong>Last In, First Out (LIFO)</strong>. Artinya data yang terakhir masuk adalah yang pertama keluar. Karena aturannya sesederhana ini, Stack sangat cepat — alokasi dan dealokasi terjadi secara otomatis dan predictable.</p><p>Tapi ada syaratnya: <strong>ukuran data harus diketahui saat compile time</strong>.</p><pre>let angka: i32 = 42;    // Stack — compiler tahu i32 selalu 4 bytes<br>let aktif: bool = true; // Stack — compiler tahu bool selalu 1 byte</pre><p>Karena ukurannya sudah pasti, compiler bisa langsung “memesan tempat” di Stack tanpa perlu berpikir dua kali. Dan ketika variabel keluar dari scope, tempatnya langsung dibebaskan secara otomatis. Tanpa GC, tanpa overhead.</p><h3>Heap: Si Fleksibel yang Butuh Manajemen</h3><p>Beda dengan Stack, Heap adalah area memori yang jauh lebih besar dan fleksibel. Data yang ukurannya tidak diketahui saat compile time atau data yang bisa tumbuh secara dinamis, tinggalnya di sini.</p><p>Tapi fleksibilitas itu ada harganya. Alokasi di Heap lebih lambat karena sistem harus mencari ruang kosong yang cukup. Dan yang paling penting: <strong>data di Heap tidak dibersihkan secara otomatis</strong>.</p><p>Di Kotlin, GC yang bertanggung jawab membersihkan Heap. Di Rust, tanggung jawab itu diatur oleh sistem Ownership dan compiler yang memastikan aturannya tidak dilanggar.</p><p>Sekarang mulai terlihat kan, kenapa Ownership itu penting? Karena tanpa aturan yang jelas, data di Heap bisa bocor atau malah dihapus dua kali.</p><pre>let nama = String::from(&quot;Taufik&quot;); // Heap — bisa tumbuh, bisa diubah</pre><h3>Jadi, Apa Bedanya &amp;str dan String?</h3><p>Nah, balik ke pertanyaan awal &amp;str vs String . Sekarang pertanyaan di awal tadi harusnya sudah mulai terjawab. &amp;str dan String sama-sama menyimpan teks tapi mereka tinggal di tempat yang berbeda, dengan karakteristik yang berbeda pula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wwl0RQ5yQRUMNfJG2O6wCQ.png" /></figure><pre>let s1 = &quot;Halo&quot;;               // &amp;str → Stack, fixed, tidak bisa diubah<br>let s2 = String::from(&quot;Halo&quot;); // String → Heap, dinamis, bisa diubah</pre><p>&amp;str adalah referensi ke teks yang sudah ada, ukurannya sudah pasti sejak compile time, jadi ia bisa hidup di Stack. Sedangkan String adalah data yang punya ownership penuh, hidup di Heap, dan bisa tumbuh secara dinamis sesuai kebutuhan.</p><h3>Visualisasi: Bagaimana Keduanya Hidup di Memori</h3><p>Di bawah ini adalah bagan visualisasi bagaimana stack dan heap hidup di memori. ptr pada bagan di bawah ini adalah pointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IlLWmRz6Bforebx0Pq-cg.png" /><figcaption>String vs &amp;str di memori</figcaption></figure><p>Stringdi Stack sebenarnya hanya menyimpan tiga hal: pointer ke data di Heap, panjang data, dan kapasitas maksimalnya. Data teksnya sendiri ada di Heap. Sedangkan &amp;str langsung menyimpan datanya di Stack karena ukurannya memang sudah pasti dari awal.</p><h3>Kapan Pakai Yang Mana?</h3><p>Aturan praktisnya sederhana:</p><ul><li><strong>Pakai </strong><strong>&amp;str</strong> — kalau teksnya sudah pasti sejak awal, fixed size, dan tidak akan berubah. Misalnya nama aplikasi, label konstanta, atau pesan error yang sudah hardcoded.</li></ul><blockquote>&#39;static artinya data ini hidup sepanjang program berjalan dan tidak pernah dihapus dari memori selama aplikasi aktif.</blockquote><pre>fn get_app_name() -&gt; &amp;&#39;static str {<br>  &quot;MyApp&quot; // teks literal, hidup sepanjang program berjalan<br>}</pre><ul><li><strong>Pakai </strong><strong>String</strong> — kalau teksnya dinamis. Sumber datanya datang dari input user, hasil network request, atau perlu dimodifikasi di tengah jalan.</li></ul><pre>fn build_log_message(user_id: &amp;str, action: &amp;str) -&gt; String {<br>   format!(&quot;[LOG] User {} melakukan {}&quot;, user_id, action)<br>}</pre><h3>Satu Warning Penting: clone() Itu Mahal</h3><p>Sebelum membahas kenapa clone() mahal, kita perlu paham dulu apa itu clone() dan kenapa ia ada.</p><p>Di <a href="https://yumtaufikhidayat.medium.com/goodbye-garbage-collector-4-mental-model-rust-yang-wajib-dipahami-seorang-android-engineer-22b4250747b6">artikel sebelumnya</a>, kita sudah membahas bahwa Rust menerapkan aturan <strong>Move</strong> yaitu ketika sebuah data dipindahkan ke variabel lain, pemilik lamanya langsung dianggap “mati” dan tidak bisa diakses lagi.</p><pre>let s1 = String::from(&quot;Halo&quot;);<br>let s2 = s1; // ownership berpindah ke s2<br><br>println!(&quot;{}&quot;, s1); // ERROR - s1 sudah mati</pre><p>Nah, bagaimana kalau kita memang butuh kedua variabel tetap hidup? Di sinilah clone() hadir sebagai solusinya.</p><pre>let s1 = String::from(&quot;Halo&quot;);<br>let s2 = s1.clone(); // s1 tetap hidup, s2 dapat salinan penuh<br><br>println!(&quot;{}&quot;, s1); // masih bisa diakses<br>println!(&quot;{}&quot;, s2); // juga bisa diakses</pre><p>clone() membuat <strong>salinan lengkap</strong> dari data yang ada di Heap dan bukan sekadar menyalin pointer-nya, tapi benar-benar menduplikasi seluruh isinya ke lokasi baru di Heap.</p><p>Dan sekarang setelah kita paham Stack vs Heap, kita bisa melihat kenapa ini bisa jadi masalah. Setiap kali clone() dipanggil, Rust harus mengalokasikan ruang baru di Heap, menyalin seluruh isinya, lalu membuat String baru di Stack yang menunjuk ke salinan tersebut.</p><p>Untuk string pendek ini mungkin tidak terasa. Tapi coba bayangkan data sensor berukuran besar, response JSON dari API, atau buffer audio yang sedang diproses maka clone() yang berlebihan bisa jadi beban nyata, terutama di perangkat Android low-end yang memorinya terbatas.</p><pre>let data = String::from(&quot;Data sensor yang sangat panjang...&quot;);<br>let salinan = data.clone(); // seluruh data di Heap diduplikasi</pre><p>Itulah kenapa Rust mendorong kita untuk lebih sering pakai <strong>Borrowing</strong> (&amp;) sebagai alternatif yang lebih efisien, pinjam datanya tanpa perlu menduplikasi.</p><h3>Kesimpulan</h3><p>Sebagai kesimpulan akhir, Stack dan Heap bukan konsep eksklusif Rust. Bahasa pemrograman C dan C++ sudah lebih dulu mengharuskan programmer mengelola memori secara manual. Yang membuat Rust berbeda adalah ia memaksa kita untuk peduli dengan Stack dan Heap, tapi sekaligus menjamin lewat compiler bahwa kita tidak bisa melakukan kesalahan yang fatal.</p><p>Sekarang kalau ada pertanyaan kenapa Rust punya dua tipe String, tentu kita sudah punya jawaban yang lengkap: karena &amp;str dan String hidup di tempat yang berbeda, dengan tanggung jawab yang berbeda pula.</p><p>Keempat mental model di <a href="https://yumtaufikhidayat.medium.com/goodbye-garbage-collector-4-mental-model-rust-yang-wajib-dipahami-seorang-android-engineer-22b4250747b6">artikel pertama</a>, Ownership, Borrowing, Shadowing, dan Slice, semuanya kini punya fondasi yang lebih kokoh. Karena pada akhirnya, semua aturan itu lahir dari satu tujuan sederhana: <strong>memastikan setiap byte di memori punya pemilik yang jelas, tanpa perlu GC untuk membereskannya.</strong></p><p>Pada artikel berikutnya, kita akan mulai berkenalan dengan <strong>Struct, Impl, dan Traits — </strong>dan kita akan melihat bagaimana data kompleks yang kita bangun sebagai Android Engineer bisa dimodelkan di Rust tanpa harus bergantung pada Class dan Inheritance.</p><h3>Referensi</h3><ol><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html">What is Ownership?</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/1.22.0/book/first-edition/the-stack-and-the-heap.html">The Stack and the Heap</a></li><li>The Rust Programming Language — <a href="https://doc.rust-lang.org/book/ch15-01-box.html">Using Box&lt;T&gt; to Point to Data on the Heap</a></li></ol><p><em>Follow saya di </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> dan </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> untuk update seputar Android Development lainnya.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c9284b5b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goodbye Garbage Collector: 4 Mental Model Rust yang Wajib Dipahami Seorang Android Engineer]]></title>
            <link>https://yumtaufikhidayat.medium.com/goodbye-garbage-collector-4-mental-model-rust-yang-wajib-dipahami-seorang-android-engineer-22b4250747b6?source=rss-b1b71b5dd036------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b4250747b6</guid>
            <dc:creator><![CDATA[Taufik Hidayat]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 00:40:43 GMT</pubDate>
            <atom:updated>2026-04-12T01:26:41.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld7bmbcuX9DF4fPJStaZ2A.png" /><figcaption>From Kotlin to Rust</figcaption></figure><p>Sebagai Android Engineer yang sudah bertahun-tahun hidup di ekosistem JVM/ART, kita sudah sangat “manja” dengan <em>Garbage Collector</em> (GC). Kita jarang pusing memikirkan <em>lifecycle</em> sebuah objek di memori. Selama tidak ada <em>static reference</em> yang bocor, GC akan membereskannya.</p><p>Namun, saat mulai menyentuh kode Rust, terutama untuk kebutuhan NDK, <em>high-performance engine</em>, atau <em>shared logic,</em> kita dipaksa untuk kembali ke dasar. Di Rust, memori bukan lagi urusan “nanti”, tapi urusan “sekarang”. Pindah dari Kotlin ke Rust itu bukan cuma soal ganti sintaks, tapi soal ganti cara pikir. Di Rust, memori adalah aset yang harus jelas siapa pemiliknya.</p><p>Berikut adalah 4 pilar utama yang wajib dipahami untuk mental modelnya.</p><h3>1. Ownership &amp; Move: Serah Terima Jabatan</h3><p>Di Kotlin, val b = a berarti kita punya dua <em>reference</em> ke satu objek di <em>Heap</em>. Di Rust, ini adalah <strong>Move</strong> dan setiap data hanya punya <strong>satu pemilik</strong>.</p><ul><li><strong>Logic:</strong> Hak milik data berpindah tangan sepenuhnya. Jika a diberikan ke b, maka a dianggap “mati” oleh <em>compiler</em>.</li><li><strong>Impact:</strong> Variabel a langsung menjadi <em>invalid</em> (hangus) dan tidak bisa diakses lagi setelah baris tersebut.</li><li><strong>“Why”:</strong> Ini cara Rust menjamin <em>memory safety</em> tanpa GC. Tidak ada skenario <em>Double Free</em> karena setiap byte di memori hanya punya satu pemilik tunggal yang bertanggung jawab menghapusnya saat <em>out of scope</em>.</li><li><strong>Code:</strong> Bagaimana variabel aslinya menjadi <em>invalid</em> setelah hak milik dipindahkan.</li></ul><pre>fn main() {<br>    // String disimpan di Heap<br>    let s1 = String::from(&quot;Hello World&quot;);<br>    <br>    // Hak milik s1 dipindahkan (Move) ke s2<br>    let s2 = s1; <br><br>    // println!(&quot;{}&quot;, s1); <br>    // ^^^ ERROR: value borrowed here after move<br>    // s1 sudah &quot;mati&quot; karena kepemilikannya sudah pindah ke s2.<br>    <br>    println!(&quot;Data ada di s2: {}&quot;, s2);<br>}</pre><ul><li>Di Kotlin, s2 = s1 hanya menyalin referensi. Di Rust, ini adalah serah terima tanggung jawab memori secara total.</li></ul><h3>2. Borrowing: Compile-Time Read-Write Lock</h3><p>Pernah kena error ConcurrentModificationException di Android? Nah itu terjadi karena kita mencoba mengubah data yang sedang dibaca oleh bagian lain secara bersamaan. Rust menyelesaikan ini di tahap kompilasi lewat aturan <strong>Borrowing (</strong><strong>&amp;)</strong>.</p><ul><li><strong>Immutable (</strong><strong>&amp;):</strong> Kamu bisa punya ribuan &quot;pembaca&quot; sekaligus, selama tidak ada yang mencoba menulis.</li><li><strong>Mutable (</strong><strong>&amp;mut):</strong> Jika ada satu bagian kode yang ingin menulis, dia harus menjadi <strong>eksklusif</strong>. Tidak boleh ada pembaca atau penulis lain yang aktif pada data tersebut.</li><li><strong>Analogi &amp; Insight:</strong> Seperti <em>Read-Write Lock</em> di database, <em>borrowing</em> mencegah <em>Data Race</em> secara prematur sejak tahap kompilasi. Di Android, anggap ini sebagai <em>Mutex</em> atau <em>Read-Write Lock</em> yang otomatis dipasang oleh <em>compiler</em>. Jika kode yang ditulis melanggar aturan ini, aplikasi tidak akan pernah bisa di-<em>build</em>.</li><li><strong>Code: </strong>Aturan eksklusivitas saat ingin mengubah data.</li></ul><pre>fn main() {<br>    let mut status = String::from(&quot;Pending&quot;);<br><br>    // Immutable borrow: Boleh banyak pembaca (read)<br>    let r1 = &amp;status;<br>    let r2 = &amp;status;<br>    println!(&quot;Status saat ini: {} dan {}&quot;, r1, r2);<br><br>    // Mutable borrow: Harus jadi satu-satunya penulis (write)<br>    let r3 = &amp;mut status;<br>    r3.push_str(&quot; - Processed&quot;);<br>    <br>    // println!(&quot;{}&quot;, r1); // ERROR: Tidak bisa baca saat sedang ada yang nulis (r3)<br>    <br>    println!(&quot;Status terbaru: {}&quot;, r3);<br>}</pre><ul><li>Aturan ini secara teknis adalah <em>Compile-time Mutex</em>. Kita tidak akan pernah bisa mengubah data yang sedang dibaca oleh fungsi lain.</li></ul><h3>3. Shadowing: Transformasi Data Tanpa “Namespace Pollution”</h3><p>Kalau biasa menulis kode di Java/Kotlin, salah satu kebiasaan buruknya adalah membuat variabel perantara yang mengotori <em>namespace</em>, seperti ageString, ageInt, ageValidated. Rust menawarkan solusi elegan yang bernama <strong>Shadowing</strong>.</p><ul><li><strong>Pattern:</strong> Kita bisa mendeklarasikan ulang variabel dengan nama yang sama menggunakan kata kunci let.</li><li><strong>Use Case:</strong> Sangat efektif untuk <em>data cleaning</em> atau konversi tipe data (misal dari input String ke i32) tanpa harus memikirkan nama variabel baru yang tidak relevan.</li><li><strong>Warning:</strong> Gunakan <em>shadowing</em> hanya untuk transformasi linear yang berdekatan. Jangan gunakan <em>shadowing</em> dalam fungsi yang terlalu panjang karena akan mengaburkan <em>traceability</em> owner utamanya.</li><li><strong>Code:</strong> Cara bersih untuk melakukan transformasi tipe data tanpa membuat variabel baru seperti amountStr, amountInt</li></ul><pre>fn main() {<br>    let amount = &quot;50000&quot;; // String dari input user<br><br>    // Shadowing untuk konversi (String -&gt; i32)<br>    let amount: i32 = amount.parse().expect(&quot;Bukan angka&quot;);<br><br>    // Shadowing untuk logika bisnis (Misal: tambah admin fee)<br>    let amount = amount + 2500;<br><br>    println!(&quot;Total transaksi: Rp{}&quot;, amount);<br>}</pre><ul><li>Gunakan ini untuk menjaga agar <em>namespace</em> tetap bersih. Variabel sebelumnya secara efektif “terkubur” oleh deklarasi baru.</li></ul><h3>4. Slice: Zero-Copy Data Views</h3><p><strong>Slice</strong> adalah referensi ke <strong>sebagian</strong> data dalam sebuah koleksi (seperti String atau Array). Untuk urusan performa, <strong>Slice (</strong><strong>&amp;str, </strong><strong>&amp;[T])</strong> adalah juaranya.</p><ul><li><strong>Sintaks:</strong> &amp;data[start..end]</li><li><strong>Efficiency:</strong> Slice hanyalah sebuah “jendela” (pointer + length) ke data asli. Saat kita memotong sebuah String, Rust tidak menduplikasi datanya di RAM. Dia cuma “jendela” yang ngintip ke data asli.</li><li><strong>Tipe:</strong> &amp;str adalah slice untuk teks, dan &amp;[i32] adalah slice untuk array angka. Sangat krusial untuk performa tinggi di aplikasi CLI atau pemrosesan data.</li><li><strong>Android Context:</strong> Bayangkan saat kita harus memproses <em>log</em> sistem atau data sensor yang ukurannya masif. Menggunakan Slice berarti kita melakukan manipulasi data secara instan tanpa beban alokasi memori tambahan (<em>Zero-copy</em>).</li><li><strong>Code:</strong> Efisiensi memori dengan mengambil “view” tanpa melakukan alokasi baru.</li></ul><pre>fn main() {<br>    let log_entry = String::from(&quot;2026-04-12 ERROR: Connection timeout&quot;);<br><br>    // Slice: Mengambil jendela (pointer + length) tanpa duplikasi data di RAM<br>    let date = &amp;log_entry[0..10];    // &quot;2026-04-12&quot;<br>    let level = &amp;log_entry[11..16];  // &quot;ERROR&quot;<br><br>    println!(&quot;Log Date: {}, Severity: {}&quot;, date, level);<br>}</pre><ul><li>Sangat krusial saat memproses data besar seperti <em>logcat</em> atau paket data jaringan. <em>Zero-copy</em> secara default adalah salah satu alasan kenapa Rust bisa secepat C++.</li></ul><h3>Perbandingan Setiap Fitur pada Kotlin dan Rust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrD5P6X3g3uWI_oKtchJ1Q.png" /></figure><h3>Perbandingan Paradigma: Kotlin vs Rust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8HrYl67V6ihHdach7exxQ.png" /></figure><h3>Kesimpulan: Mengapa Rust Terasa “Ribet”?</h3><p>Belajar Rust di awal memang terasa seperti berdebat dengan rekan <em>Senior Developer</em> yang sangat cerewet di tahap <em>Code Review</em>. Namun, setiap “garis merah” yang diberikan oleh <em>Borrow Checker</em> adalah satu <em>bug production</em> yang berhasil kita cegah sebelum aplikasi sampai ke tangan <em>user</em>.</p><p>Bagi kita yang terbiasa menangani sistem yang kompleks atau aplikasi skala besar, keamanan tipe data dan manajemen memori yang prediktif di Rust memberikan kontrol presisi yang luar biasa. Ini memungkinkan kita menghindari alokasi memori runtime yang tidak perlu, yang sangat krusial di perangkat Android low-end untuk mencegah crash aplikasi akibat Out of Memory (OOM).</p><p>Dengan Rust, performa tinggi bukan lagi sekadar fitur, tapi sebuah kebutuhan arsitektur yang bisa kita capai dengan aman.</p><p>Keempat mental model di atas: <strong>Ownership</strong>, <strong>Borrowing</strong>, <strong>Shadowing</strong>, dan <strong>Slice</strong>; semuanya punya satu fondasi yang sama: pemahaman tentang di mana data itu sebenarnya hidup di memori. Pada artikel berikutnya, kita akan membedah perbedaan <strong>Stack</strong> dan <strong>Heap</strong>, dan mengapa ini adalah kunci untuk benar-benar “klik” dengan cara Rust berpikir.</p><h3>Referensi</h3><ol><li><strong>Ownership and Move:</strong> <a href="https://doc.rust-lang.org/rust-by-example/scope/move.html">https://doc.rust-lang.org/rust-by-example/scope/move.html</a></li><li><strong>References and Borrowing:</strong> <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html</a></li><li><strong>Scope and Shadowing:</strong> <a href="https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html">https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html</a></li><li><strong>The Slice Type:</strong> <a href="https://doc.rust-lang.org/book/ch04-03-slices.html">https://doc.rust-lang.org/book/ch04-03-slices.html</a></li></ol><p><em>Follow saya di </em><a href="https://medium.com/@yumtaufikhidayat"><em>Medium</em></a><em> dan </em><a href="https://www.linkedin.com/in/taufik-hidayat/"><em>LinkedIn</em></a><em> untuk update seputar Android Development lainnya.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b4250747b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>