{
  "id": 18521035,
  "title": "The MustCreate Pattern for Go Tests",
  "url": "https://urgent.news/2026/11/06/the-mustcreate-pattern-for-go-tests",
  "topic": "tech",
  "section": "Tech",
  "published": "2026-11-06T15:37:00.000Z",
  "source": {
    "name": "Lobsters",
    "slug": "lobsters",
    "url": "https://mtlynch.io/notes/go-must-create-pattern/"
  },
  "original_language": "en",
  "account": "I recently found a helpful method to make Go tests more readable and less repetitive. When writing tests for ReadUser, I call NewUsername with a known valid value, yet still faced verbose error-checking code to assure the compiler that everything is alright. Until a few months ago, this verbose error checking was avoided by using a helper function like MustCreateUsername that wraps NewUsername, expecting it to never return a non-nil error value. The implementation of MustCreateUsername is straightforward: The helper function approach worked well, but it becomes cumbersome as the codebase grows, resulting in numerous MustCreateFoo and MustCreateBar helpers for every type in the application. In 2022, Go 1.18 introduced generics, and I appreciated the idea of generics but rarely encountered problems where generics were the solution. Recently, I realized that generics could be the better way to address my sprawling MustCreateX issue. Instead of defining a separate helper for each type, I created a single, generic MustCreate test helper, simplifying the tests to: The power of the generic MustCreate function lies in its ability to handle different types. When I invoke MustCreate in my tests, RawInput represents the type of the raw username value, and CreatedValue signifies the return type. It's equivalent to an implementation that appears as follows: What if constructors have more than one parameter? In such cases, I define an additional helper called MustCreate2: The implementation of MustCreate2 mirrors MustCreate but with an extra type for the second parameter: The MustCreate pattern is not groundbreaking, but it's a technique that has significantly improved my Go tests and reduced some monotonous work in my development process.",
  "summary": null,
  "key_points": [],
  "editors_take": null,
  "illustration": null,
  "coverage": {
    "outlets": 1,
    "also_reported_by": []
  },
  "ai_generated": true,
  "disclaimer": "Summaries, key points and the editor’s take are written by software from other outlets’ reporting and may contain errors — always check the linked original."
}