Go

[Go]Multiline strings in Go

Night-Owl 2023. 2. 18. 21:34
반응형

 

 

Go 에서 여러 줄 문자열을 작성하는 방법에 대해서 알아보자.

1. Interpreted string

큰 따옴표와 함께 \n 와 같은 이스케이프 문자를 사용하면 여러 줄 문자열을 사용할 수 있다.

func main() {
    lines := "Build simple, secure, scalable systems with Go\n" +
        "- An open-source programming language supported by Google\n" +
        "- Easy to learn and great for teams\n" +
        "- Built-in concurrency and a robust standard library\n" +
        "- Large ecosystem of partners, communities, and tools"

    fmt.Print(lines)
}

결과:

Build simple, secure, scalable systems with Go
- An open-source programming language supported by Google
- Easy to learn and great for teams
- Built-in concurrency and a robust standard library
- Large ecosystem of partners, communities, and tools

 

 

 

2. Raw string

Raw strings은 큰 따옴표 대신 Backtick (`) 문자를 감싸서 표현한다.

package main

import "fmt"


func main() {
    lines := `Build simple, secure, scalable systems with Go
- An open-source programming language supported by Google
- Easy to learn and great for teams
- Built-in concurrency and a robust standard library
- Large ecosystem of partners, communities, and tools`

    fmt.Print(lines)
}

결과:

Build simple, secure, scalable systems with Go
- An open-source programming language supported by Google
- Easy to learn and great for teams
- Built-in concurrency and a robust standard library
- Large ecosystem of partners, communities, and tools

 

 

Raw strings에서는  \n\t 와 같은 이스케이프 문자가 의미가 없다.

package main

import "fmt"

func main() {
	lines := `Build simple,\nsecure, scalable systems with Go\n
\t- An open-source programming\nlanguage supported by Google
\t- Easy to learn and great for teams
\t- Built-in concurrency and a robust standard library
\t- Large ecosystem of partners, communities, and tools`

	fmt.Print(lines)
}

결과:

Build simple,\nsecure, scalable systems with Go\n
\t- An open-source programming\nlanguage supported by Google
\t- Easy to learn and great for teams
\t- Built-in concurrency and a robust standard library
\t- Large ecosystem of partners, communities, and tools

 

 

Raw strings에서는 들여쓰기 역시 그대로 보존한다.

package main

import "fmt"

func main() {
	lines := `{
  "employee": {
    "name": "sonoo",
    "salary": 56000,
    "married": true
  }
}  `

	fmt.Print(lines)
}

결과:

{
  "employee": {
    "name": "sonoo",
    "salary": 56000,
    "married": true
  }
}
반응형