create an immutable variable of type string in go

In Go, we can create an immutable variable of type string using the const keyword. const declares a new constant variable with a specified type and a value that can't be changed. Here's an example:

main.go
const message string = "Hello, world!" // declaring a constant variable with a value that can't be changed
107 chars
2 lines

In the above code, we declare a constant variable called message with the type string and initialize it with a value of "Hello, world!". Once the variable is initialized, we cannot change its value.

We can also declare and initialize a constant variable without explicitly specifying its type as shown below:

main.go
const message = "Hello, world!" // declaring a constant variable without specifying its type
93 chars
2 lines

However, Go's type inference system will automatically detect the type of the constant from the value it is initialized with.

gistlibby LogSnag