Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
string
data
communitycreator

What is type string in Golang?

Sheza Naveed

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

string in Golang is a set of all strings that contain 8-bit bytes. By default, strings in Golang are UTF-8 encoded.

Variable of type string is enclosed between double-quotes. The type string variable’s value is immutable.


The value assigned to the type string variable can be empty but cannot be nil.

Code

Example 1

The code below shows how to declare a variable of type string.

package main
import "fmt"
func main() {
var sentence string
sentence = "Hello From Educative"
fmt.Printf("Sentence : %s\n", sentence);
fmt.Printf("Data type of sentence is %T\n", sentence);
}

Explanation

The keyword var is written followed by the variable name, and then we state the variable datatype which is string.

Example 2

The code below shows another way to declare a string variable.

package main
import "fmt"
func main() {
var sentence = "Hello From Educative"
fmt.Printf("Sentence : %s\n", sentence);
fmt.Printf("Data type of sentence is %T\n", sentence);
}

Explanation

We have not explicitly mentioned that the variable is of type string as we have directly initialized it with a value enclosed between double-quotes. sentence still gets stored as a variable of type string.

RELATED TAGS

go
string
data
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring