# Refactor Go Code using Comby

<p className="subtitle">
	This guide explains how to use Comby to refactor Go code in a batch change.
</p>

To refactor Go code using Comby in a batch change, use Sourcegraph's [structural search](/code-search/types/structural) and [Comby](https://comby.dev/) to rewrite Go statements.

From:

```go
fmt.Sprintf("%d", number)
```

To:

```go
strconv.Itoa(number)
```

The statements are semantically equivalent, but the latter is more precise.

Since the replacements could require importing the `strconv` package, it uses [`goimports`](https://godoc.org/golang.org/x/tools/cmd/goimports) to update the list of imported packages in all `*.go` files.

## Prerequisites

<Callout type="tip">
	It's recommended to use the latest version of Sourcegraph when working with
	Batch Changes.
</Callout>

Before you start, it's better to read the following docs:

-   [Batch Changes Quickstart](/batch-changes/quickstart)
-   [How to create and run a Batch Spec?](/batch-changes/create-a-batch-change)

## Create the batch spec

Save the following batch spec YAML as `sprintf-to-itoa.batch.yaml`:

```yaml
name: sprintf-to-itoa
description: |
    This batch change uses [Comby](https://comby.dev) to replace `fmt.Sprintf` calls
    in Go code with the equivalent but clearer `strconv.Iota` call.

on:
    - repositoriesMatchingQuery: lang:go fmt.Sprintf("%d", :[v]) patterntype:structural

steps:
    - run: comby -in-place 'fmt.Sprintf("%d", :[v])' 'strconv.Itoa(:[v])' .go -matcher .go -exclude-dir .,vendor
      container: comby/comby
    - run: goimports -w $(find . -type f -name '*.go' -not -path "./vendor/*")
      container: unibeautify/goimports

changesetTemplate:
    title: Replace fmt.Sprintf with equivalent strconv.Itoa
    body: This batch change replaces `fmt.Sprintf` with `strconv.Itoa`
    branch: batch-changes/sprintf-to-itoa
    commit:
        message: Replacing fmt.Sprintf with strconv.Iota
    published: false
```

## Create the batch change

-   In your terminal, run the following command:

```shell
src batch preview -f sprintf-to-itoa.batch.yaml
```

-   Wait for it to run and compute the changes for each repository
-   Open the preview URL that the command printed out
-   Examine the preview. Confirm that the changesets are the ones you intended to track. If not, edit the batch spec and then re-run the command above
-   Click the **Apply** button to create the batch change
-   Feel free to then publish the changesets (i.e., create pull requests and merge requests) by [modifying the `published` attribute in the batch spec](/batch-changes/batch-spec-yaml-reference#changesettemplatepublished) and re-running the `src batch preview` command
