Skip to content

Instantly share code, notes, and snippets.

@cgt
Created May 13, 2023 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgt/2c63208e63a6a720a31021b14f2503e1 to your computer and use it in GitHub Desktop.
Save cgt/2c63208e63a6a720a31021b14f2503e1 to your computer and use it in GitHub Desktop.
Error parameter in extracted functions
func foo(r io.Reader) error {
    data, err := io.ReadAll(r)
    if err != nil {
        return err
    }
    _, err = fmt.Print(data)
}

Extracting the fmt.Print line to a function it becomes:

func foo(r io.Reader) error {
    data, err := io.ReadAll(r)
    if err != nil {
        return err
    }
    funcName(err, data)
}

func funcName(err error, data []byte) {
    _, err = fmt.Print(data)
}

GoLand thinks it has to add err as a parameter to funcName because the err variable is reused in foo, but we obviously don't want to pass the old err in as a parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment