golang Strings can be seen as a collection of characters. A string can be of length 1 (one character), but its usually longer. A string is always written in double qoutes.

This means a string variable in golang can hold text: words, sentences, books

Programming languages have variables. These variables have a data type
A variable can be of the data type string.

Download PDF

String example

String variable

In the example below we use golang to print text.
First define a string variable, then print the variable.

1
2
3
4
5
6
7
8
package main

import "fmt"

func main() {
var str1 = "This is a string variable!"
fmt.Printf(str1)
}

Multiple lines

Generally there are 2 ways to print multiple lines.

Method 1. call display function x times,
Method 2. use the newline character inside the string

Both of these are common in programming.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import "fmt"

func main() {
var str1 = "This is a string variable!"

// 1: function calls
fmt.Printf(str1)
fmt.Printf(str1)

// 2: use newline character
fmt.Printf("Hello World")

}

Video

Video tutorial below

Exercises

  1. Create a program with multiple string variables
  2. Create a program that holds your name in a string.

Download Answers