이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 3. The gofmt formatting tool


Instead of a style guide, the Go programming language uses the gofmt code formatting tool. gofmt automatically formats your code according to the Go layout rules.

3.1. Prerequisites

3.2. Formatting code

You can use the gofmt formatting tool to format code in a given path. When the path leads to a single file, the changes apply only to the file. When the path leads to a directory, all .go files in the directory are processed.

Procedure

  • To format your code in a given path, enter:

    $ gofmt -w <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to format.

    Note

    To print the formatted code to standard output instead of writing it to the original file, omit the -w option.

3.3. Previewing changes to code

You can use the gofmt formatting tool to preview changes done by formatting code in a given path. The output in unified diff format is printed to standard output.

Procedure

  • Show differences in your code in a given path:

    $ gofmt -d <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to compare.

3.4. Simplifying code

You can use the gofmt formatting tool to simplify your code.

Procedure

  1. To simplify code in a given path, enter:

    $ gofmt -s -w <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to simplify.

  2. To apply the changes, enter:

    $ gofmt -w <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to format.

3.5. Refactoring code

You can use the gofmt formatting tool to refactor your code by applying arbitrary substitutions.

Procedure

  1. To refactor your code in a given path, enter:

    $ gofmt -r -w <rewrite_rule> <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to refactor and <rewrite_rule> with the rule you want it to be rewritten by.

  2. To apply the changes, enter:

    # gofmt -w <code_path>
    Copy to Clipboard Toggle word wrap

    Replace <code_path> with the path to the code you want to format.

맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat