[go] Go에서 bool을 문자열로 변환하는 방법은 무엇입니까?

를 사용하여 bool호출 isExist된 것을 string( true또는 false) 로 변환하려고하는데 string(isExist)작동하지 않습니다. Go에서이를 수행하는 관용적 방법은 무엇입니까?



답변

strconv 패키지 사용

문서

strconv.FormatBool(v)

func FormatBool (b bool) string FormatBool
은 b 값에 ​​따라 “true”또는 “false”를 반환합니다.


답변

두 가지 주요 옵션은 다음과 같습니다.

  1. strconv.FormatBool(bool) string
  2. fmt.Sprintf(string, bool) string"%t"또는 "%v"포맷터.

참고 strconv.FormatBool(...)입니다 상당히 보다 빠른 fmt.Sprintf(...)다음과 같은 기준에 의해 입증으로 :

func Benchmark_StrconvFormatBool(b *testing.B) {
  for i := 0; i < b.N; i++ {
    strconv.FormatBool(true)  // => "true"
    strconv.FormatBool(false) // => "false"
  }
}

func Benchmark_FmtSprintfT(b *testing.B) {
  for i := 0; i < b.N; i++ {
    fmt.Sprintf("%t", true)  // => "true"
    fmt.Sprintf("%t", false) // => "false"
  }
}

func Benchmark_FmtSprintfV(b *testing.B) {
  for i := 0; i < b.N; i++ {
    fmt.Sprintf("%v", true)  // => "true"
    fmt.Sprintf("%v", false) // => "false"
  }
}

다음으로 실행 :

$ go test -bench=. ./boolstr_test.go
goos: darwin
goarch: amd64
Benchmark_StrconvFormatBool-8       2000000000           0.30 ns/op
Benchmark_FmtSprintfT-8             10000000           130 ns/op
Benchmark_FmtSprintfV-8             10000000           130 ns/op
PASS
ok      command-line-arguments  3.531s


답변

다음 strconv.FormatBool과 같이 사용할 수 있습니다 .

package main

import "fmt"
import "strconv"

func main() {
    isExist := true
    str := strconv.FormatBool(isExist)
    fmt.Println(str)        //true
    fmt.Printf("%q\n", str) //"true"
}

또는 다음 fmt.Sprint과 같이 사용할 수 있습니다 .

package main

import "fmt"

func main() {
    isExist := true
    str := fmt.Sprint(isExist)
    fmt.Println(str)        //true
    fmt.Printf("%q\n", str) //"true"
}

또는 다음과 같이 작성하십시오 strconv.FormatBool.

// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
    if b {
        return "true"
    }
    return "false"
}


답변

그냥 사용 fmt.Sprintf("%v", isExist)하면 거의 모든 유형의 경우처럼.


답변