Make an error from a string in Go

This is an example Go program demonstrating how to make an error from a string.

package main

import (

func macaroni(x string) (i bool, err error) {
        i = strings.Contains(x, "macaroni")
        if ! i {
                return i, errors.New("No macaroni found")

func main() {
        i, err := macaroni("macarena")
        if err != nil {
                fmt.Printf("Error: %s\n", err)
        } else {
                fmt.Printf("Macaroni is at %d\n", i)


The output of the example looks like this:

Error: No macaroni found

Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer