Go/Study record
Sprint는 어떤 때 사용되는가?
Gopythor
2022. 3. 26. 20:21
728x90
반응형
- 통상적으로 변수 등이 String으로 사용된다면 큰 차이는 없음.
- 그러나 String이 아닌 형태가 서로 결합한다면 문제가 발생함.
Code
func main() {
sstring := fmt.Sprint("Hello ", "World")
nstring := "Hello World"
fmt.Println(sstring)
fmt.Println(nstring)
}
https://go.dev/play/p/WO415NpCkSl
- 문제는 String이 아닌 Integer 등이 혼합될 때이다.
Code
func main() {
Sequence := 254
sstring := fmt.Sprintf("Sequence number %d is on hold", Sequence)
fmt.Println(sstring)
nstring := "Sequence number " + Sequence + "is on hold"
fmt.Println(nstring)
}
https://go.dev/play/p/pm_Vc-iKQUZ
- 첫번째 sstring 변수는 문제없이 출력을 이끌어내지만, nstring 변수는 타입 오류로 에러를 출력한다.
Result
./prog.go:12:13: invalid operation: "Sequence number " + Sequence (mismatched types untyped string and int)
- 억지로 사용하고 싶다면 strconv.Itoa를 사용해도 된다.
Code
func main() {
Sequence := 254
sstring := fmt.Sprintf("Sequence number %d is on hold", Sequence)
fmt.Println(sstring)
nstring := "Sequence number " + strconv.Itoa(Sequence) + " is on hold"
fmt.Println(nstring)
}
https://go.dev/play/p/8CsnrUY_kzE
Result
Sequence number 254 is on hold
Sequence number 254 is on hold
728x90
반응형