더북(TheBook)

gofmt 도구

gofmt는 Go를 설치하면 제공되는 콘솔용 프로그램이다. 명령 프롬프트에 gofmt -h를 입력해서 gofmt의 사용법을 확인해 보자.

명령 프롬프트

$ gofmt -h

usage: gofmt [flags] [path ...]

-cpuprofile string
write cpu profile to this file

-d  display diffs instead of rewriting files

-e  report all errors (not just the first 10 on different lines)

-l  list files whose formatting differs from gofmt's

-r  string
rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')

-s  simplify code

-w  write result to (source) file instead of stdout

명령 프롬프트에 gofmt 파일명을 입력하면 스타일이 맞춰진 코드를 볼 수 있다.

명령 프롬프트

$ gofmt prog.go

package main
  
import "fmt"
  
func main() {
    type Rect struct {
        width int  //width
        height int //height
    }
  
    r := Rect{1, 2}
    fmt.Println(r.width*2 + r.height*2)
}

-w 옵션을 사용하면 스타일이 맞춰진 코드를 원본 소스 파일에 다시 저장한다.

명령 프롬프트

$ gofmt -w prog.go

 

$ cat prog.go

package main
  
import "fmt"
  
func main() {
    type Rect struct {
        width int  //width
        height int //height
    }
  
    r := Rect{1, 2}
    fmt.Println(r.width*2 + r.height*2)
}

대부분의 개발용 에디터에는 소스 코드를 저장할 때 gofmt로 스타일을 정돈해주는 플러그인이 있다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.