본문 바로가기
golang

Formatting in golang

by marble25 2023. 9. 3.

golang은 C-style의 포맷팅을 지원한다.

하지만 좀 더 고수준의 언어이기 때문에 좀 더 다양한 타입에 대한 출력을 지원한다.

이에 golang에서의 출력 포맷을 정리해볼 필요를 느껴서 정리해 본다.

참고: https://pkg.go.dev/fmt

General

%v	the value in a default format
	when printing structs, the plus flag (%+v) adds field names
%#v	a Go-syntax representation of the value
%T	a Go-syntax representation of the type of the value
%%	a literal percent sign; consumes no value
%v 인스턴스 출력 {1 2}
%+v 인스턴스 출력 + 필드명 추가 {x: 1 y: 2}
%#v 코드 스니펫 출력 main.point{x: 1 y: 2}
%T 타입 출력 main.point

자주 사용되는 타입

%t	the word true or false
%d	base 10 integer
%f	decimal point but no exponent, e.g. 123.456
%s	the uninterpreted bytes of the string or slice
%q	quoted string escaped with go syntax
%t 불린 값 true
%d 10진수 값 123
%f 실수 값 78.900000
%s 문자열 값 "string”
%q escaped된 문자열 "\"string\"”

일반적으로는 %v를 사용하면 다음과 같이 표현된다고 하니 편리하게 %v를 써보면 좋을 것 같다.

bool:                    %t
int, int8 etc.:          %d
uint, uint8 etc.:        %d, %#x if printed with %#v
float32, complex64, etc: %g
string:                  %s
chan:                    %p
pointer:                 %p

'golang' 카테고리의 다른 글

Go context 파헤치기  (0) 2023.09.29
goroutine 파헤치기  (0) 2023.09.23
Internal package in golang  (0) 2023.09.03
Go 언어를 활용한 분산 서비스 개발  (0) 2023.07.23
실무에 바로 쓰는 Go 언어 핸즈온 가이드  (0) 2023.07.12