Golang program to illustrate the creation of strings


In this tutorial, we will see how strings are created in Golang. There are different ways to create strings which we will learn via some examples. In Golang a string is a sequence of variable-width characters where each character is represented by one or more bytes.

Method 1: Using double Quotes with Shorthand Declaration

In this method, we will learn about how to create strings using shorthand declaration. Let’s dive into the code to understand it.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a function main and further create a shorthand declaration of string.

Step 3 − Print the string using fmt.Println() function which is used for printing the statements in Go language.

Example

Golang program to create string using double quotes with shorthand declaration

package main
import "fmt"
func main() {
   val := "Hi I am an Engineer"
   
   // Displaying strings
   fmt.Println("String val: ", val)
}

Output

String val:  Hi I am an Engineer

Method 2: Using Double Quotes with var Keyword

In this method, we will see how to create strings using var keyword. The output will be printed using fmt.Println() function.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a function main and further create a string using val keyword.

Step 3 − Print the string using fmt.Println() function which is used for printing the statements in Go language.

Example

Golang program to create string using double quotes with var keyword

package main
import "fmt"
func main() {
   var val string
   val = "Hi I am an engineer"
   
   // Displaying strings
   fmt.Println("String val: ", val)
}

Output

String val:  Hi I am an engineer

Method 3: Create String Using Backticks

In this method, we will create string using backticks and the output will be printed using fmt.Println() function. Let’s have a look how to do this.

Algorithm

Step 1 − Create a package main and import fmt package in the program.

Step 2 − Create a function main and further create a string using val keyword with backticks.

Step 3 − Print the string using fmt.Println() function which is used for printing the statements in Go language.

Example

Golang program to create string using backticks

package main
import "fmt"
func main() {
   val := `Hi,I am an engineer`

   // Displaying strings
   fmt.Println("String val: ", val)
}

Output

String val:  Hi,I am an engineer

Conclusion

In the above tutorial, we created strings using three methods. In the first method we used the main function with shorthand declaration, in the second example we used double quotes with Val keyword and in the third example we used backticks with Val keyword. Hence, all the methods executed successfully.

Updated on: 13-Feb-2023

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements