What is type string in Golang?
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
stringvariable can be empty but cannot be nil.
Code
Example 1
The code below shows how to declare a variable of type string.
package mainimport "fmt"func main() {var sentence stringsentence = "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 mainimport "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.