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.
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);}
The keyword var
is written followed by the variable name, and then we state the variable datatype which is string
.
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);}
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
.