Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

Golang(Go) 데이터를 콜솔에 출력,데이터의 형태를 변경하는 패키지(strings,strconv,fmt)

GOLANG, 20222 min read

fmt package

배경

go 코드를 사용하면서 가장 자주 썼던 패키지는 fmt패키지 인거 같다.

코드를 작성하고 결과가 예상과 일치하는지 또는 또는 데이터의 형태를 변환할때 사용했었다.

x := 123
fmt.Printf("%b\n",x) //integer => binary
//1111011
fmt.Printf("%o\n",x)//8진법
//173
fmt.Printf("%d\n",x)//bytes 16진수
//123
fmt.Sprintf("123 %s", "test")
// 123 test

strconv package

strconv.FormatUint(uint64(u), 10)

  • var n uint = 123 를 문자열로 변환
  • strconv.FormatUint(uint64(u), 10)

strconv.ParseInt

  • string to int64
  • id, _ := strconv.ParseInt(str, 10, 64)
참고

https://stackoverflow.com/questions/57187889/how-to-convert-uint-type-into-string-type-in-golang


strings package

Golang(Go) golang strings 패키지 기록 date: 2021-08-05

  1. strings.Replace
strings.Replace("테스트''", "'", "", -1)
//-1 은 문자 내부에 모든 ' 요소를 변경해줍니다.
strings.Replace("2022-06-17"","-", "")
// "-" 를 제거함

어드민 화면에서 서비스로 조회 데이터를 요청합니다.이떄 프론트에서 Query Parameter 으로 기간 데이터 "2022-06-17" 를 보냅니다. /users?queryFrom="2022-06-01"&&queryTo="2022-06-17" 이렇게 보내진 내용은 서비스코드에서 ctx.Bind를 통해 값을 받고 mysql 로 조회할 때 "-" 때문에 조회되지 않는 문제가 있어서 strings.Replace 를 통해 변경했다.

  1. strings.Trim
strings.Trim("test test", " ")
//공백을 제거할 떄 사용
  1. strings.Fields()

s := strings.Fields("a b") s[1] 은 a

  • 공백을 기준으로 문자열을 문자열 슬라이스로 저장
  1. strings.Join(roles, ",")
  • roles 은 []string 인데 ,를 통해 배열을 , 로 구분하는 string 으로 만들어 준다
  • func Join(element []string, sep string) string
  1. strings.NewReader(requestBody)
  • 테스트케이스에서 requestBody := {"code": "1"} 를 NewRequest 의 매개변수 로 쓸 수 있도록 *Reader 로 변경해준다.
  • req := httptest.NewRequest(echo.POST, "/api/test", strings.NewReader(requestBody))
참고

https://www.socketloop.com/tutorials/golang-remove-dashes-or-any-character-from-string http://pyrasis.com/book/GoForTheReallyImpatient/Unit46/02

How to format current time using a yyyyMMddHHmmss format ? time pkg 정리 https://stackoverflow.com/questions/32140980/get-the-first-and-last-day-of-a-year-from-a-timestamp

© 2024 by GwiyeomGo Tech Blog. All rights reserved.